SalesforceBlue

Feel the rhythm of Salesforce

LWC

Using Lightning EmpApi Module In LWC

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.

If you would like to get more information regarding streaming events then feel free to explore this excellent post.

Alright, let’s create a prerequisite Platform event for this example.

Please refer to the details given in the below table:

Object NameSend_Message
API NameSend_Message__e
Publish BehaviorPublish Immediately
Custom Field: Api NameMessage__c
Custom Field: Data TypeLong Text Area(32768)

Now let’s create a component(LWC) named as empApiExample and add the following code. Later add this component to the Home page.

<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>
        </div>
        <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>
    </lightning-card>

    <lightning-card title="Message received from platform event">
        <div class="slds-m-around_medium">
            Message:  
        </div>
    </lightning-card>
</template>
import { LightningElement } from 'lwc';
import {
    subscribe,
    unsubscribe,
    onError,
    setDebugFlag,
    isEmpEnabled,
} from 'lightning/empApi';

export default class EmpApiExample extends LightningElement {
    channelName = '/event/Send_Message__e';
    isSubscribeDisabled = false;
    isUnsubscribeDisabled = !this.isSubscribeDisabled;
    subscription = {};
    message;

    // 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 = (response) => {
            console.log('New message received: ', JSON.stringify(response));
            this.message = response.data.payload.Message__c;
            // 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
        });
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
     <targets>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Let’s understand what we did:

In the file empApiExample.html we have added two buttons that will subscribe to the given channel which is /event/Send_Message__e.

In the file empApiExample.js we first import the required references from the lightning/empApi module

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

handleSubscribe() call is subscribing to the given channel. Here we are also providing a callback method that will be invoked once there is a new event message received.

 // Handles subscribe button click
    handleSubscribe() {
        // Callback invoked whenever a new event message is received
        const messageCallback = (response) => {
            console.log('New message received: ', JSON.stringify(response));
            this.message = response.data.payload.Message__c;
            // 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);
        });
    }

handleUnsuscribe() let you unsubscribe() to the given channel.

    // 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
        });
    }

registerErrorListener() registering listeners to the errors that the server returns.

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

Now let’s see our empApiExample component in action.

Open the developer console as we are going to manually publish the platform event we have created above. Enter the following snippet in the developer console and execute it.

Eventbus.publish(
new Send_Message__e (
	Message__c = 'Have an awesome day :)'
));

On your Home page you would be getting an output like the one below:

emp api demo

So by now, you are familiar with platform events and how to use the lightning/empApi module in your lwc.

Now let’s create a real-time multiplayer game out of it 🙂 Read this post to explore more – Create Multiplayer TIC TAC TOE Game Using LWC And Platform Events

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


3 thoughts on “Using Lightning EmpApi Module In LWC

  • This is not working in my org. Nothing happened when I click on Subscribe button.

    Reply
    • Pankaj Agrahari

      Hi Naveen, Can you please extract the components which you have implemented and shared the zip file at salesforceblue@gmail.com so I can take a look and share the findings?

      Reply
    • Pankaj Agrahari

      Also can you please confirm if after clicking subscribe you have executed this snippet from the developer console –

      Eventbus.publish(
      new Send_Message__e (
      Message__c = ‘Have an awesome day :)’
      ));

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *