Lightning Web Component and Streaming API
1. Features
- Subscribe Push Topics, Platform Events.
- Easy to use LWC APIs.
- Easier control to subscribe, unsubscribe and check the status of the subscription.
- This component can be used in the Lightning(Aura) Component as well.
2. Introduction
LWC Streaming API component let you subscribe streaming API channel in an easy way. You just need to provide the channel name. Its onmessage event let you get the payload from streaming API.
<c-lwc_streaming_api
channel="/topic/NewContactCreated"
api-version="45.0"
debug=true
onmessage={handleMessage}
onerror={handleError}
class="lwc_streaming_api-1">
</c-lwc_streaming_api>
Attributes
This component has three types of attributes.
- channel: This is a required attribute. We need to define the channel name in this attribute. Ex: /topic/NewContactCreated and event/My_Event__e.
- api-version: This is an optional attribute. It tells that which API version will be used for cometd. If you omit this then it will take 45.0 as the default version.
- debug: This is an optional attribute. It takes the boolean value as the parameter. It allows you to see various logs on browser console. By default, this is set to false if you omit this.
Events
This component has two types of events.
- onmessage: This event gets fired when any streaming API sends the payload/message. You need to define the handler for your component to get the value from this event. You can get payload using this: event.detail.payload
- onerror: This event fire if any kind of error happens at the LWC streaming API component. You need to define the handler for your component to get the error message from this event. You can get the error using this: event.detail.error
Note: You can define debug=true to see all the console results as well.
Methods
This component has three types of methods that you can use to re-subscribe, unsubscribe and check the status of the subscription. By default when component rendered get completed, it subscribes to the streaming channel.
- subscribe(): Subscribe the channel if it was destroyed or unsubscribe. You cannot Subscribe a channel if it already Subscribed. Multiple subscriptions will send multiple payload event from the streaming API.
- unsubscribe(): It unsubscribes the channel. You can subscribe to a channel if it is unsubscribed. We can use this to stop receiving payloads.
- checkConnection(): This method returns true or false. If the channel is subscribed then it will return the true else false.
3. Demo Video
4. Example Code
Deploy the code of streaming API from Github using deploy to Salesforce button. As this repo is already in sfdx format, you can directly use with scratch orgs by cloning it to local.
Step 1. Create a push topic using the Developer Console. Copy the following code and execute in the developer console. What will it do? It will create a push topic name NewContactCreated. Whenever a contact record gets created. It will send the payload to the onmessage event. Read PushTopic Events from salesforce document.
PushTopic pushTopic = new PushTopic();
pushTopic.Name = 'NewContactCreated';
pushTopic.Query = 'select Id,Name from Contact';
pushTopic.ApiVersion = 45.0;
pushTopic.NotifyForOperationCreate = true;
pushTopic.NotifyForOperationUpdate = false;
pushTopic.NotifyForOperationUndelete = false;
pushTopic.NotifyForOperationDelete = false;
pushTopic.NotifyForFields = 'All';
insert pushTopic;
Step 2. Create a Lightning Web Component name as lwc_streaming_demo. Copy and paste the following code to the files.
Note: Add the target configuration in the meta XML file. so you can add your demo component to the using the app builder. In my case, I have added the component to the home page.
lwc_streaming_demo.js
import { LightningElement,track } from 'lwc';
export default class Lwc_streaming_demo extends LightningElement {
@track error = '';
@track payload = '';
@track isConnectionOn;
//Handles the error
handleError(event){
//Error is coming in the event.detail.error
this.error = JSON.stringify(event.detail.error);
}
//Handles the message/payload from streaming api
handleMessage(event){
//Message is coming in event.detail.payload
this.payload = this.payload + JSON.stringify(event.detail.payload);
}
//This method is subscribing the channel
restart(){
this.template.querySelector('.lwc_streaming_api-1').subscribe();
}
//This method is unsubscribing the channel
destroy(){
this.template.querySelector('.lwc_streaming_api-1').unsubscribe();
this.payload = '';
this.error = '';
}
//This method is checking if the channel is subscribed or not
checkConnection(){
this.isConnectionOn = this.template.querySelector('.lwc_streaming_api-1').checkConnection();
}
}
lwc_streaming_demo.html
<template>
<c-lwc_streaming_api
channel="/topic/NewContactCreated"
api-version="45.0"
debug=true
onmessage={handleMessage}
onerror={handleError}
class="lwc_streaming_api-1">
</c-lwc_streaming_api>
<lightning-button label="Destroy Connection" onclick={destroy}></lightning-button>
<lightning-button label="Restart Connection" onclick={restart}></lightning-button>
<lightning-button label="Check Connection" onclick={checkConnection}></lightning-button>
<div style="background: white;padding: 50px;">
<div style="margin:20px;">
Payload
<br/>
{payload}
</div>
<div style="margin:20px;">
Error:
<br/>
{error}
</div>
<div style="margin:20px;">
Is Connection On:
<br/>
{isConnectionOn}
</div>
</div>
</template>
lwc_streaming_demo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="lwc_streaming_demo">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Step 3. Open your demo component. Now create some contact records and you will see the message/payload on the screen.
Step 4 (Another way to use): If you want to try it with platform events. Create a platform event object. Subscribe it using below code.
<c-lwc_streaming_api
channel="/event/Test_Event__e"
api-version="45.0"
debug=true
onmessage={handleMessage}
onerror={handleError}
class="lwc_streaming_api-1">
</c-lwc_streaming_api>
Here Test_Event__e is my platform event object name.
Now create platform event records using below code:
Test_Event__e te = new Test_Event__e ();
te.Test_Field__c = 'test data';
Database.SaveResult sr = EventBus.publish(te);
I have used a custom text field (Test_Field__c) in the platform event.
Get Above code from the gist.