Lightning Chat component using Streaming API and Generic events
Hello and welcome! 😀
Finally, I managed to document this! *phew*
So in this article, we will see how we can create a lightning chat component to exchange messages in real time between internal org users.
Key concepts and elements:
Streaming API
Generic Events
Lightning:empApi
Apex
Lots of JavaScript and SLDS
Streaming API
Streaming API enables streaming of events using push technology and provides a subscription mechanism for receiving events in near real time. We can think of Streaming API as a radar which keeps tracks of events.
Streaming API subscription mechanism supports multiple types of events, including PushTopic events, generic events, platform events, and Change Data Capture events.
Generic Events
As the name suggests, these events are generic in some sense. These events do not have a predefined schema.
What makes these events interesting for our chat component is that they can be used to publish events to a targeted set of users.
Defining Streaming channel to stream the events
StreamingChannel ch = new StreamingChannel();/* The
format
of the channel name for generic streaming is
/u/
ChannelName
*/
ch.Name = '/u/ChatChannel'; insert ch;
To create the streaming channel, we simply execute this code in anonymous window.
Publishing generic event is on a streaming channel
To push a generic event on a channel, we must first define the request body of the event and then publish the event using a POST callout to the Streaming API.
-Request body of Generic event:
{ "pushEvents": [ { "payload": " <Message to publish> ", "userIds": [] } ] }
So a request body contains an attribute called “pushEvents” which contains the list of all Generic events. Each generic event contains two attributes, namely; payload and userIds.
payload: Contains the message content which we want to send.
userIds: a list of strings containing User IDs.
Lightning:empApi
This is a lightning base component introduced by Salesforce in Winter 19 release. Using this component, we will subscribe to the our Streaming channel. Refer the component library, to understand how to subscribe to a channel. The code snippet provided is pretty easy to understand.
Data flow in the Chat component

DEMO:

Code:
P.S. If you find some scope of improvement in the code, suggestions are welcomed! 😀
Thank you!

.png)




Comments