EP-31 | empAPI in Lightning Web Components Salesforce | LWC Stack ☁️⚡️



 LWC Stack is Lightning Web Component tutorial series by Salesforce MVP Kapil Batra. In this series you will find LWC tutorials from beginner to intermediate level.

So if you are working on it or planning to learn LWC then this video series is for you. Let's learn and grow together !

Please check complete code below from LWC Stack EP-31


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. This component requires API version 44.0 or later.

The lightning/empApi module uses a shared CometD connection, enabling you to run multiple streaming apps in a single browser session. The connection is not shared among multiple user sessions.

In a component's Javascript file, import methods from the lightning/empApi module using this syntax.

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

The available methods are described below.

This example subscribes to a streaming channel when you click the Subscribe button. It logs received event messages to the JavaScript console in your browser. The Unsubscribe button lets you stop the subscription and stop receiving event messages. This example uses the default streaming channel of /event/Test__e and assumes that the Test__e platform event is defined. Replace the default value with the desired channel name. In my case the event name is CustomEvent__e.


Create a platform event and add some custom fields


HTML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<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>
      <br />
      <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>
      <br />
      <br />
      <p>Message from Salesforce Bolt - {messageBody}</p>
    </div>
  </lightning-card>
</template>


JavaScript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { LightningElement, track } from "lwc";
import {
  subscribe,
  unsubscribe,
  onError,
  setDebugFlag,
  isEmpEnabled
} from "lightning/empApi";

export default class EmpAPIListner extends LightningElement {
  @track messageBody = "";
  channelName = "/event/CustomEvent__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() {
    const thisReference = this;
    // Callback invoked whenever a new event message is received
    const messageCallback = function (response) {
      thisReference.messageBody = response.data.payload.message__c;
      console.log("###New message received ", 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
    });
  }
}


Apex in Anonymous Window in developer console

1
2
CustomEvent__e event = new CustomEvent__e(message__c = 'You are Awesome...');
Database.SaveResult result = EventBus.publish(event);


Output


Source : https://developer.salesforce.com/docs/component-library/bundle/lightning-emp-api/documentation

Checkout complete video tutorial below


 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

0 Comments