What's Lightning Message Service [LMS] in LWC?

Let's look at how to use Lightning Message Service in LWC.

Before Lightning Message Service there was PubSub which was used to send data from one Lightning Web Component to another Lightning Web Component.

That approach of using PubSub to send data was a bit tedious and lengthy from the developer's point of view, also, we were able to only send data from one LWC to another LWC and nothing beyond that.

In LWC we will be using LMS when we want to send data from one LWC to another LWC which are not in hierarchy!

Not only that, with LMS data can be sent to any entity (LWC/ Aura Component/ VF pages) using the same standard of communication as long as they are subscribed to the Message Channel (Think of message channel as Youtube channel).

In general, the route that Salesforce takes is, it takes the current trending thing in the market and Salesforce tries to simplify it to the core, and then it gives that back to the developer community.

As an example, you can take ReactJS. Salesforce took inspiration from ReactJs and made it a lot more simple which is LWC.

Likewise, I personally believe Salesforce took the inspiration of LMS from Redux which is basically used to manage application state, and gave us back something called Lightning Message Service (this is purely my interpretation).

Let's understand what's LMS in simple words.

Lightning Messaging Service

In a way, LMS works similar to how notifications work on Youtube.

When a user subscribes to a channel, any data that's published after subscribing will be pushed and notified to the subscribed (unless the subscriber unsubscribes from it).

This is exactly how notifications in Youtube work, when you subscribe to a Youtube channel and when the YouTuber uploads a new video you get a notification. When you unsubscribe to the channel the user will not get notifications when a new video is uploaded by the YouTuber.

So in Salesforce when an LWC or Aura Component or Visualforce subscribes to a Message Channel, when data is published to the MessageChannel automatically all the subscribers will get notified about the new data, as simple as that.

Hope this was helpful!