How to Subscribe/Un-Subscribe event in LWC

 

How to Subscribe/Un-Subscribe event in LWC

In this post, we will discuss about how to subscribe/un-subscribe events (Whether its Platform event or Change Data Capture) in LWC using ‘lightning/empApi’.


To subscribe or un-subscribe event in LWC, we need to use “empAPI” component in your Lightning web component. To use the empApi methods in your Lightning web component, import the methods from the lightning/empApi module as given below.

The lightning/empApi module provides access to methods for subscribing to a streaming channel and listening to event messages. All streaming channels are supported, including channels for platform events, PushTopic events, generic events, and Change Data Capture events.

Syntax

import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled 
from 'lightning/empApi'; }

subscribe method

Subscribes to a given channel and returns a promise that holds a subscription object, which you use to unsubscribe later.

subscribe(this.channelName, -1, meessageCallBack)
channel (String) — The channel name to subscribe to.
replayId (number) — Indicates what point in the stream to replay events from. Specify -1 to get new events from the tip of the stream, -2 to replay from the last saved event, or a specific event replay ID to get all saved and new events after that ID.
onMessageCallback(function) — A callback function that’s invoked for every event received.

unsubscribe method

Unsubscribes from the channel using the given subscription object and returns a promise. The result of this operation is passed in to the callback function.

unsubscribe(this.subscription, callBackFunction)
subscription(object) — Subscription object that the subscribe call returned.
callback(function) — A callback function that’s called with a server response for the unsubscribe call.

onError method

Registers a listener to errors that the server returns.

callback(function) — A callback function that’s called when an error response is received from the server for handshake, connect, subscribe, and unsubscribe meta channels.


Demonstration

HTML

<!-- Sachin Jha -->
<template>
<lightning-card title="Subscribe Events" icon-name="custom:custom14">
<div class="slds-p-horizontal_small">
<lightning-input type="text"
variant="standard"
name="subscriptionChannelName"
label="Channel Name"
value={channelName}
placeholder="Type channel name here....."
onchange={handleChannelName}>

</lightning-input>
</div>
<br>
<div class="slds-p-horizontal_small">
<lightning-button variant="success"
label="Subscribe"
title="subscribe"
onclick={handleSubscribeButton}
disabled={isSubscribeDisable}>

</lightning-button>
&nbsp; &nbsp;
<lightning-button variant="destructive"
label="Un-Subscribe"
title="unsubscribe"
onclick={handleUnSubscribeButton}
disabled={isUnSubscribeDisable}>

</lightning-button>
</div>

<br><br>

<table class="slds-table slds-table_cell-buffer slds-table_bordered" aria-labelledby="element-with-table-label other-element-with-table-label">
<thead>

<tr class="slds-line-height_reset">
<th class="" scope="col">
<div class="slds-truncate" title="Entity Name">Entity Name</div>
</th>
<th class="" scope="col">
<div class="slds-truncate" title="Change Type">Change Type</div>
</th>
<th class="" scope="col">
<div class="slds-truncate" title="Changed Record Ids">Changed Record Ids</div>
</th>
<th class="" scope="col">
<div class="slds-truncate" title="Changed Fields">Changed Fields</div>
</th>
</tr>

</thead>

<tbody>

<tr class="slds-hint-parent" lwc:if={subscriptionResult}>

<th data-label="Entity Name" scope="row">
<div class="slds-truncate" title="entity">
{subscriptionResult.data.payload.ChangeEventHeader.entityName}
</div>
</th>

<td data-label="Change Type">
<div class="slds-truncate" title="change type">
{subscriptionResult.data.payload.ChangeEventHeader.changeType}
</div>
</td>

<td data-label="Changed Record Ids">
<div class="slds-truncate" title="change record id">
<template for:each={subscriptionResult.data.payload.ChangeEventHeader.recordIds} for:item='record'>
<div key={record}>
{record}
</div>
</template>
</div>
</td>

<td data-label="Changed Fields">
<div class="slds-truncate" title="change fields">
<template for:each={subscriptionResult.data.payload.ChangeEventHeader.changedFields} for:item='data'>
<div key={data}>
{data}
</div>
</template>
</div>
</td>

</tr>

</tbody>
</table>
<div slot="footer">
<strong>Payload of the new message in JSON </strong> <br>
{subscriptionResultJsonFormat}
</div>
</lightning-card>
</template>

JS

// Sachin Jha
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi'

export default class SubscribeEvent extends LightningElement {
subscriptionResult
subscription = {}
subscriptionResultJsonFormat
channelName = '/data/AccountChangeEvent' // for platform event - /event/yourPlatformEvenName__e
isSubscribeDisable = false
isUnSubscribeDisable = !this.isSubscribeDisable

handleChannelName(event){
this.channelName = event.target.value
console.log('Channel Name:- '+this.channelName);
}

// Handles subscribe button click
handleSubscribeButton(){
// Callback invoked whenever a new event message is received
const meessageCallBack = (response)=>{
console.log('Message Received:- '+JSON.stringify(response));
// Response contains the payload of the new message received
this.subscriptionResult = response
this.subscriptionResultJsonFormat = JSON.stringify(response);
}

// Invoke subscribe method of empApi. Pass reference to messageCallback
subscribe(this.channelName, -1, meessageCallBack).then((response)=>{
console.log('response:- '+JSON.stringify(response));
// response will give subscription object, later we can use it for unsubsibe
this.subscription = response
this.toggleButton(true)
})

}

// Handles unsubscribe button click
handleUnSubscribeButton(){
this.toggleButton(false)

// Call back function for unsubscibe event
const callBackFunction = (response)=>{
console.log('un-subscribe() method invoked:- '+JSON.stringify(response));
}

// Invoke unsubscribe method of empApi
unsubscribe(this.subscription, callBackFunction)

}

toggleButton(toggle){
this.isSubscribeDisable = toggle
this.isUnSubscribeDisable = !toggle
}

}

meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>


Follow me on linkedIn and Twitter for such more related post


Comments