Lightning Message Service (LMS) in Lightning Web Component – With Fun Modi-Rahul Mitron Project

A cartoon characters with text Description automatically generated with medium confidence

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:

LinkedIn

Subscribe to my YouTube Channel

Follow my Blog-sfdcamplified

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.

dSQuMLApS9Xgkt3tdQEVjw 6nGqH3leb17Ktp7a5gzs1zZfxCZ vyfsxvWqyfnLUrb0GDqm4wjLnSMHMQlqkzCtmJusRdSWRHftG DINL07L8uBg6V45 QykACyObTV5DvvASbs3SG6

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!”

PM Narendra Modi's favourite word 'Mitron' makes it to Oxford dictionary. Here's what it means

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!

Rahul Gandhi bats for Net neutrality without being on social media - India Today

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.

A screenshot of a computer Description automatically generated

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

  1. Open vs code
  2. Go to force/app/main/default folder in your Salesforce DX project.
  3. Create a new folder named messageChannels if it doesn’t already exist.
  4. Inside the messageChannels folder, create a new file with the desired name for your message channel. Let’s call it mitroMessageChannel.messageChannel-meta.xml

A screenshot of a computer Description automatically generated

  1. In mitronMessageChannel.messageChannel- meta.xml add master label, description, isexposed to true.

A screen shot of a computer program Description automatically generated

6.Update the manifest/package.xml file by adding the lightningMessageChannel

A screenshot of a computer program Description automatically generated

7.Deploy this to Dev Org.

Step 2: Create Publisher Component to Publish Message

A person with a beard and mustache Description automatically generated

Steps in nutshell:

A white card with black text Description automatically generated

Let’s dive deep!

Water Sports Clipart-cartoon style boy jumping from divingboard into the pool

Complete Publish Component Code

A screenshot of a computer Description automatically generated

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.

Angry Bee Cartoon Mascot Character Holding A Stop Sign.Illustration Isolated On White Royalty Free SVG, Cliparts, Vectors, and Stock Illustration. Image 36141799.

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

A cartoon of a person with glasses Description automatically generated

Steps in nutshell:

A close up of a paper Description automatically generated

Let’s dive deep!

The Diving Board | Mr. Bean | Cartoons for Kids | WildBrain Kids - YouTube

Complete Publish Component Code

A screenshot of a computer screen Description automatically generated

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

  1. Import Subscribe, MessageContext from lightning/messageService

import MITRON_MESSAGE_CHANNEL from ‘@salesforce/messageChannel/mitronMessageChannel__c’;

  1. 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’;

  1. Wire a messageContext

@wire(MessageContext)
messageContext

  1. In Connectedcallback()- call this.subscribeToMessageChannel() method.

connectedCallback() {

this.subscribeToMessageChannel();

}

  1. 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.

Krecik Stop Sticker - Krecik Stop - Discover & Share GIFs

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.

 

A yellow and orange text Description automatically generated

If you have any suggestions or feedback.

Feel free to connect with me on:

LinkedIn

Subscribe to my YouTube Channel

Follow my Blog – sfdcAmplified

 

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes