November 13, 2020

Salesforce Platform Event Subscription in LWC

Sample code:
 
HTML:
<template>
    <lightning-card title="EmpApi Example" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
            <p>Use the buttons below to subscribe and unsubscribe to a streaming channel!</p>
            <lightning-input label="Channel Name" value={channelName}
                onchange={handleChannelName}></lightning-input>
            <lightning-button variant="success" label="Subscribe" title="Subscribe"
                onclick={handleSubscribe} disabled={isSubscribeDisabled}
                class="slds-m-left_x-small"></lightning-button>
            <lightning-button variant="destructive" label="Unsubscribe" title="Unsubscribe"
                onclick={handleUnsubscribe} disabled={isUnsubscribeDisabled}
                class="slds-m-left_x-small"></lightning-button>
        </div>
    </lightning-card>
</template>

 
JavaScript:
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from 'lightning/empApi';

export default class PlatformEventMonitor extends LightningElement {
    channelName = '/event/Sample__e';
    isSubscribeDisabled = false;
    isUnsubscribeDisabled = !this.isSubscribeDisabled;

    subscription = {};

    // Tracks changes to channelName text field
    handleChannelName(event) {
        this.channelName = event.target.value;
    }

    // Initializes the component
    connectedCallback() {       
        // Register error listener       
        this.registerErrorListener();      
    }

    // Handles subscribe button click
    handleSubscribe() {
        // Callback invoked whenever a new event message is received
        const messageCallback = function(response) {
            console.log('New message received: ', JSON.stringify(response));
            // Response contains the payload of the new message received
        };

        // Invoke subscribe method of empApi. Pass reference to messageCallback
        subscribe(this.channelName, -1, messageCallback).then(response => {
            // Response contains the subscription information on subscribe call
            console.log('Subscription request sent to: ', JSON.stringify(response.channel));
            this.subscription = response;
            this.toggleSubscribeButton(true);
        });
    }

    // Handles unsubscribe button click
    handleUnsubscribe() {
        this.toggleSubscribeButton(false);

        // Invoke unsubscribe method of empApi
        unsubscribe(this.subscription, response => {
            console.log('unsubscribe() response: ', JSON.stringify(response));
            // Response is true for successful unsubscribe
        });
    }

    toggleSubscribeButton(enableSubscribe) {
        this.isSubscribeDisabled = enableSubscribe;
        this.isUnsubscribeDisabled = !enableSubscribe;
    }

    registerErrorListener() {
        // Invoke onError empApi method
        onError(error => {
            console.log('Received error from server: ', JSON.stringify(error));
            // Error contains the server-side error
        });
    }
}

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


Sample Platform Event:

 
 
 
Apex Code:
Sample__e objEvent = new Sample__e( Name__c = 'Testing' );
EventBus.publish( objEvent ); 

Execute the above code in Anonymous apex window.


No comments:

Post a Comment