[LWC] Publish-Subscribe Model in Lightning Web Components using Lightning Message Service | Communicate Between Two Components in LWC
Salesforce's Publish-Subscribe Model (Pub-Sub) is a communication pattern that enables seamless interaction between components without requiring a direct parent-child relationship.
This model is implemented using the Lightning Message Service (LMS), which provides a standard way to exchange data between LWCs, Aura components, and even Visualforce pages. It allows for updates, communication across different trees in the DOM, and data sharing between components.
There is another way to use pubsub functionality using PubSub Library.
The benefits of using Pub-Sub with LMS include decoupled components, cross-domain communication, and scalability. Best practices include using the Lightning Message Service, keeping message payload minimal, and unsubscribing from disconnected channels.
The easiest way to communicate between components that aren’t in the same DOM tree is to use Lightning message service (lightning/messageService
). Consider using the publish-subscribe mechanism with the pubsub
module only if you're working in containers that don't support Lightning Message Service. The pubsub
module is no longer officially supported or actively maintained.
To communicate between components in a single Lightning page or across
multiple pages, set up a Lightning message channel. The advantage over
the publish-subscribe mechanism is that message channels aren’t
restricted to a single page. Any component in a Lightning Experience
application that listens for events on a message channel updates when it
receives a message. It works between Lightning web components, Aura
components, and Visualforce pages in any tab or in any pop-out window in
Lightning Experience. It also works across namespaces.
To implement Publish-Subscribe model in lwc using Lightning Message Service follow the below steps:
Create Two Components
ComponentA and componentB
Create a Lightning Message Channel to use as a medium to communicate.
A Lightning Message Channel represents a secure channel to communicate across UI technologies, such as Lightning Web Components, Aura Components, and Visualforce.
Create a message channel if you want to:
- Communicate across the DOM within a Lightning page.
- Communicate between Visualforce pages embedded in the same Lightning page, Aura components, and Lightning web components, including components in a utility bar and pop-out utilities.
- Choose whether a component subscribes to messages from the entire application, or from only the active area.
Step 1: Create a folder in force-app/main/default/ the name of the folder should be messageChannels
Step 2: create a file in the force-app/main/default/messageChannels/
and the filename should be strictly in the given format:
[messageChannelName].messageChannel-meta.xml
Import this Lightning Message Channel in both the components
import messageChannelName from "@salesforce/messageChannel/messageChannelName__c";
Note: There are different syntax to import lightning message channel in lwc and limitations for using in managed package.
Refer Official Documentation's : doc1, doc2
In component A, Add the following imports
import { publish, MessageContext } from "lightning/messageService";
import recordSelected from "@salesforce/messageChannel/Record_Selected__c";
Add the following code as well:
@wire(MessageContext)
messageContext;
handleOnSendData(event) {
const payload = { recordId: event.target.Id };
publish(this.messageContext, recordSelected
, payload);
}
In Component B, Add the following imports
import { subscribe, unsubscribe, APPLICATION_SCOPE, MessageContext,} from "lightning/messageService";
import recordSelected from "@salesforce/messageChannel/Record_Selected__c";
Add the following code as well:
@wire(MessageContext)
messageContext;
//subscribe to listen for published data
subscribeToMessageChannel() {
if (!this.subscription) {
this.subscription = subscribe(
this.messageContext, recordSelected,
(message) => this.handleMessage(message),
{ scope: APPLICATION_SCOPE }
);
}
}
//unsubscribe when component is disconnected from dom
disconnectedCallback() {
this.unsubscribeToMessageChannel();
}
unsubscribeToMessageChannel() {
unsubscribe(this.subscription); this.subscription = null;
}
Example: Get all the contacts and opportunities of the selected account record.
Component A:
Component B:
ParentComponent:
Github: @AbhishekSinha7/PubSubLWC/LightningMessageService
Comments
Post a Comment