0

I need to send multiple message into one component via Lightning message system using one message channel.Is it possible or i must use multiple message channel? I tried to google, but didn't found any answer. So it must be like that and catch in one subsctiber component

import { LightningElement, wire } from 'lwc';
import messageChannel from '@salesforce/messageChannel/SampleMessageChannel__c';
import {publish, MessageContext} from 'lightning/messageService'

export default class Publisher1 extends LightningElement {

    @wire(MessageContext)
    messageContext;

    handleButtonClick(event) {
        let message = {messageText: 'First'};
        publish(this.messageContext, messageChannel, message);
    }
}

    import { LightningElement, wire } from 'lwc';
    import messageChannel from '@salesforce/messageChannel/SampleMessageChannel__c';
    import {publish, MessageContext} from 'lightning/messageService'
    
    export default class Publisher2 extends LightningElement {
    
        @wire(MessageContext)
        messageContext;
    
        handleButtonClick(event) {
            let message = {messageText: 'Second'};
            publish(this.messageContext, messageChannel, message);
        }
    }

Subscriber

import { LightningElement, wire, api } from 'lwc';
import messageChannel from '@salesforce/messageChannel/SampleMessageChannel__c';
import { subscribe, MessageContext } from 'lightning/messageService';

export default class Subscriber extends LightningElement {

    subscription = null;
    @api msg = 'test';

    @wire(MessageContext)
    messageContext;

    connectedCallback() {
        this.handleSubscribe();
    }

    handleSubscribe() {
        if (this.subscription) {
            return;
        }
        this.subscription = subscribe(this.messageContext, messageChannel, (message) => {
            this.msg = message.messageText;
            console.log(message.messageText);
        });
    }
    
}
2

If you want to use one channel, you'll be limited to one handler that will then have to dispatch to other methods based on the contents of the message. Using multiple channels would probably make the code easier to read. Ultimately, the end result would be just about identical in terms of complexity and legibility, so choose whichever you prefer.

2
  • Thanks, i thought its bad to use multiple channels.
    – Terdivi
    Sep 27 at 6:23
  • @Terdivi There's no limits I know of regarding multiple channels, it's just the documentation doesn't show any examples.
    – sfdcfox
    Sep 27 at 6:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.