Hi, my name is Smriti Sharan. I am an avid blogger and youtuber. I break down complex concepts with fun relatable real-time examples so that learning is fun. Wow!!!
You can connect with me on:
Subscribe to my YouTube Channel
Lightning Message Service
Topics Covered:
- Lightning Message Service Overview
- Explain LMS in Fun Way with ‘Modi Mitron Project’
- Create Message Channel
- Publish on Message Channel
- Subscribe in Message Channel
The Lightning Message Service (LMS) which was introduced in Winter ’20 by Salesforce is used to communicate between components that are not directly related in the component hierarchy.
No matter where we fire our technology all other technology should be able to subscribe to it. Using LMS, we can enable conversations between Visualforce, Aura, and Lightning Web Components (LWC) including components in a popup utility bar. Publisher component publishes / broadcasts the data, component which receives the data is subscriber component.
Fun Time. Yay!
Let me explain it to you in a fun way! Let’s begin.
Let’s dive into a fun, hypothetical scenario that will make understanding the concept very easy. Here’s how we picture it:
Imagine Narendra Modi and Rahul Gandhi are like components from different parties, BJP, and Congress respectively. They’re part of distinct systems, just like components that can’t communicate directly with each other.
Now, let’s say they’re both at an assembly meeting where they need to share information, but due to protocol (or, in our case, architectural constraints), they cannot communicate directly. How do they manage to exchange their views? That’s where the Salesforce Lightning Message Service (LMS) comes into picture.
So even though Modi and Rahul are from separate party components, LMS allows them to publish and receive (subscribe) messages.
Terminology Around Lightning Message service
Let’s take a closer look at this diagram and the scenario with Narendra Modi and Rahul Gandhi to understand the concept of the Lightning Message Service (LMS) in Salesforce:
1.Publish: This represents Narendra Modi’s side. In our scenario, Modi wants to share the message ‘Mitron’ in the assembly meeting. He uses the ‘Publish’ mechanism of LMS, which allows him to send out his message without specifying who the recipients should be.
It’s like standing at a podium with a loudspeaker and announcing, “MITRON!”
2. Message Channel: This is the medium through which the message is transmitted.
3. Subscribe: On the other end, we have Rahul Gandhi. He is interested in hearing what Modi has to say, so he ‘Subscribes’ to the channel. By subscribing, Rahul doesn’t have to be in direct contact with Modi. He simply needs to be tuned into the right ‘frequency’ to hear the ‘Mitron’ message whenever Modi decides to publish it.
It’s like turning on a radio to a specific station!
So, when Modi decides to ‘Publish’ his message, it’s sent out to the ‘Message Channel’. Rahul, having ‘Subscribed’ to this channel, receives the message wherever he may be in the assembly hall.
Demo Time
So now we are clear basic concepts. Let’s create some fun project.
Yes, you are right, we are going to recreate the above project ‘Modi Mitron’. Wow.
Can learning be more fun?
Steps to Create ‘Modi Mitron’ Lightning Message Service
Step 1: Create a Message Channel
- Open vs code
- Go to force/app/main/default folder in your Salesforce DX project.
- Create a new folder named messageChannels if it doesn’t already exist.
- Inside the messageChannels folder, create a new file with the desired name for your message channel. Let’s call it mitroMessageChannel.messageChannel-meta.xml
- In mitronMessageChannel.messageChannel- meta.xml add master label, description, isexposed to true.
6.Update the manifest/package.xml file by adding the lightningMessageChannel
7.Deploy this to Dev Org.
Step 2: Create Publisher Component to Publish Message
Steps in nutshell:
Let’s dive deep!
Complete Publish Component Code
mitronPublish.html
<template>
<lightning-card title=”Publisher” icon-name=”custom:custom63″>
<img src={mitronmsgsentUrl} class=”image” alt=”Modi” />
<div class=”slds-p-around_medium”>
<lightning-button variant=”destructive” label=”Publish ‘MITRON’ Message”
onclick={publishMessage}>
</lightning-button>
</div>
</lightning-card>
</template>
mitronPublish.js
import { LightningElement,wire } from ‘lwc’;
import { publish, MessageContext } from ‘lightning/messageService’;
import MITRON_MESSAGE_CHANNEL from ‘@salesforce/messageChannel/mitronMessageChannel__c’;
import mitronmsgsent from ‘@salesforce/resourceUrl/mitronmsgsent’;
export default class MitronPublish extends LightningElement {
mitronmsgsentUrl = mitronmsgsent;
// Injects the message context into the component
@wire(MessageContext)
messageContext;
// Method to publish the message
publishMessage() {
const payload = { message: ‘MITRON’ };
publish(this.messageContext, MITRON_MESSAGE_CHANNEL, payload);
}
}
mitronPublish.js-meta.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<LightningComponentBundle xmlns=”http://soap.sforce.com/2006/04/metadata”>
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
Understanding Code Line by Line
1.Create a Lightning Web Component with Name ‘MitronPublish’
2. Import message channel name. To publish messages on a message channel from a lightning web component, including the “@Salesforce” symbol is necessary. Append _c after MessageChannel Name
import MITRON_MESSAGE_CHANNEL from ‘@salesforce/messageChannel/mitronMessageChannel__c’;
3.Import message service features like publish, Message Context. Publish method is imported so as to publish the message
import {publish, MessageContext} from ‘lightning/messageService’;
4.Define the Scope of the Message Service
The Lightning message service lets you define the scope of where subscribing components receive messages in your application.
For Lightning web components, the scoping feature is available only when using @wire adapter
When we put @wire(MessageContext) above a property in the component, like messageContext, we are setting up a permanent connection to the LMS. Whenever the component is on the page, it’s automatically tuned into the LMS and ready to send or receive messages.
@wire(MessageContext)
messageContext
5. Publish Message Channel
// Method to publish the message
publishMessage() {
const payload = { message: ‘MITRON’ };
publish(this.messageContext, MITRON_MESSAGE_CHANNEL, payload);
}
}
To publish message, we have publish() method in Lightning message service’s.
Stop Scrolling. Publish Method is important, so understand carefully.
publish() method accept 3 parameter :-
1. Message Context (Type Object)
2. Message Channel (Type Object)
3. Message Payload (The message payload is a JSON object)
Let’s understand with context to ‘Modi Mitron’ Project
1. Modi steps into the messageContext – the assembly hall.
2. He sends his ‘Mitron’ message over the messageChannel – the radio frequency that everyone has tuned into.
3. The ‘message’ itself travels across this channel and reaches Rahul.
In Salesforce Terminology
messageContext :- The MessageContext object provides information about the Lightning web component that is using the Lightning message service. Get this object via the MessageContext wire adapter or via createMessageContext().
messageChannel :- To import a message channel, use the scoped module @salesforce/messageChannel. To create a message channel in an org, use the LightningMessageChannel metadata type.
message:- A serializable JSON object containing the message published to subscribers. A message can’t contain functions or symbols.
Step 3: Create Subscriber Component to Subscribe to Message Channel
Steps in nutshell:
Let’s dive deep!
Complete Publish Component Code
mitronSubscribe.html
<template>
<template if:true={isRahulStanding}>
<lightning-card title=”Subscriber” icon-name=”custom:custom63″>
<img src={rahulstandingUrl} class=”image” alt=”Rahul” />
<div class=”slds-p-around_medium”>
<p>Waiting for Message</p>
</div>
</lightning-card>
</template>
<template if:true={isMitronMsgReceived}>
<lightning-card title=”Subscriber” icon-name=”custom:custom63″>
<img src={mitronmsgreceivedUrl} class=”image” alt=”Rahul” />
<div class=”slds-p-around_medium”>
<p>Message Received: {receivedMessage}</p>
</div>
</lightning-card>
</template>
</template>
mitronSubscribe.js
// subscriberComponent.js
import { LightningElement, wire } from ‘lwc’;
import { subscribe, MessageContext } from ‘lightning/messageService’;
import MITRON_MESSAGE_CHANNEL from ‘@salesforce/messageChannel/mitronMessageChannel__c’;
import rahulstanding from ‘@salesforce/resourceUrl/rahulstanding’;
import mitronmsgreceived from ‘@salesforce/resourceUrl/mitronmsgreceived’;
export default class MitronSubscribe extends LightningElement {
rahulstandingUrl = rahulstanding
mitronmsgreceivedUrl = mitronmsgreceived
isRahulStanding = true;
isMitronMsgReceived = false;
subscription = null;
receivedMessage = ”;
// Injects the message context into the component
@wire(MessageContext)
messageContext;
// Subscribe to the message channel
subscribeToMessageChannel(){
if(this.subscription==null){
this.subscription = subscribe(
this.messageContext,
MITRON_MESSAGE_CHANNEL,
(message) => this.handleMessage(message)
);
}
}
connectedCallback() {
this.subscribeToMessageChannel();
}
handleMessage(message) {
this.isRahulStanding = false;
this.isMitronMsgReceived = true;
this.receivedMessage = message ? message.message : ‘No message received’;
}
}
mitronSubscribe.js-meta.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<LightningComponentBundle xmlns=”http://soap.sforce.com/2006/04/metadata”>
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
Understanding Code Line by Line
1. Create a Lightning Web Component to Subscribe to Message
- Import Subscribe, MessageContext from lightning/messageService
import MITRON_MESSAGE_CHANNEL from ‘@salesforce/messageChannel/mitronMessageChannel__c’;
- Import subscribe and message context. In order to create a subscribe component, we need to import the Subscribe method.
import { subscribe, MessageContext } from ‘lightning/messageService’;
- Wire a messageContext
@wire(MessageContext)
messageContext
- In Connectedcallback()- call this.subscribeToMessageChannel() method.
connectedCallback() {
this.subscribeToMessageChannel();
}
- In subscribeToMessageChannel() method pass this.messageContext, Mitron_Message & message
To subscribe message channel, we use subscribe() method
subscribeToMessageChannel(){
if(this.subscription==null){
this.subscription = subscribe(
this.messageContext,
MITRON_MESSAGE_CHANNEL,
(message) => this.handleMessage(message)
);
}
}
Let’s Understand Subscribe Method in Detail
To subscribe to message, we have subscribe() method in Lightning message service’s.
Stop Scrolling. Subscribe Method is also very important, so understand carefully.
subscribe() method accept 4 parameters :-
1. Message Context (Type Object)
2. Message Channel (Type Object)
3. Listener (Type function)
4. Subscriber Options (Type Object)
In Salesforce Terminology
messageContext :- The MessageContext object provides information about the Lightning web component that is using the Lightning message service. Get this object via the MessageContext wire adapter or via createMessageContext().
messageChannel :- To import a message channel, use the scoped module @salesforce/messageChannel. To create a message channel in an org, use the LightningMessageChannel metadata type.
listener :- A function that handles the message once it is published. It waits for a message to arrive and then does something with that message, like Rahul deciding how to respond to Modi’s announcements.
subscriberOptions :- (Optional) An object that, when set to {scope: APPLICATION_SCOPE}, specifies the ability to receive messages on a message channel from anywhere in the application. Import APPLICATION_SCOPE from lightning/messageService
For instance, Rahul wants to make sure he and his colleagues don’t miss Modi’s message no matter where they are in the assembly, he’d use ‘subscriberOptions’. This means the message isn’t just heard in the main hall but anywhere within the assembly building, ensuring wide coverage.
In nutshell
- Modi’s ‘Mitron’ message is sent out into the ‘messageContext’
- it travels along the ‘messageChannel’ (radio frequency)
- It is picked up by Rahul’s ‘listener’ (his attentive ear).
- The ‘subscriberOptions’ ensure that everyone who needs to hear the message can, no matter where they are.
If you have any suggestions or feedback.
Feel free to connect with me on:
Subscribe to my YouTube Channel
Follow my Blog – sfdcAmplified