Emp API

lightning/empApi

Work with the EmpJs Streaming API library using the lightning/empApi module, which subscribes to a streaming channel and listens to event messages using a shared CometD connection for a single user session. The lightning/empApi module is supported only in desktop browsers and requires API version 44.0 or later.

For Use In

Lightning Experience

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.

The lightning/empApi module uses a shared CometD connection, enabling you to run multiple streaming apps in a single browser session. The connection isn’t shared across user sessions in other browsers. The lightning/empApi module only supports one user per browser. Multiple user sessions aren’t supported in one browser.

To use the CRM Analytics API in your component, import the functions in your component’s JavaScript file.

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

subscribe 

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

ParameterTypeDescription
channelstringThe channel name to subscribe to.
replayIdnumberIndicates 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.
onMessageCallbackfunctionA callback function that’s invoked for every event received.

unsubscribe 

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. The result object holds the successful boolean field which indicates whether the unsubscribe operation was successful. The result fields are based on the CometD protocol for the unsubscribe operation. See CometD Reference Doc.

ParameterTypeDescription
subscriptionobjectSubscription object that the subscribe call returned.
callbackfunctionA callback function that’s called with a server response for the unsubscribe call.

onError 

Registers a listener to errors that the server returns.

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

setDebugFlag 

Set to true or false to turn console logging on or off respectively.

ParameterTypeDescription
flagbooleanSet to true or false to turn console logging on or off respectively.

isEmpEnabled 

Returns a promise that holds a Boolean value. The value is true if the EmpJs Streaming API library can be used in this context; otherwise false.

Usage 

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.

1<template>
2    <lightning-card title="EmpApi Example" icon-name="custom:custom14">
3        <div class="slds-m-around_medium">
4            <p>
5                Use the buttons below to subscribe and unsubscribe to a
6                streaming channel!
7            </p>
8            <lightning-input
9                label="Channel Name"
10                value={channelName}
11                onchange={handleChannelName}
12            ></lightning-input>
13            <lightning-button
14                variant="success"
15                label="Subscribe"
16                title="Subscribe"
17                onclick={handleSubscribe}
18                disabled={isSubscribeDisabled}
19                class="slds-m-left_x-small"
20            ></lightning-button>
21            <lightning-button
22                variant="destructive"
23                label="Unsubscribe"
24                title="Unsubscribe"
25                onclick={handleUnsubscribe}
26                disabled={isUnsubscribeDisabled}
27                class="slds-m-left_x-small"
28            ></lightning-button>
29        </div>
30    </lightning-card>
31</template>

In the component’s JavaScript, event handlers invoke empApi methods.

1import { LightningElement } from "lwc";
2import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from "lightning/empApi";
3
4export default class EmpApiLWC extends LightningElement {
5  channelName = "/event/Test__e";
6  isSubscribeDisabled = false;
7  isUnsubscribeDisabled = !this.isSubscribeDisabled;
8
9  subscription = {};
10
11  // Tracks changes to channelName text field
12  handleChannelName(event) {
13    this.channelName = event.target.value;
14  }
15
16  // Initializes the component
17  connectedCallback() {
18    // Register error listener
19    this.registerErrorListener();
20  }
21
22  // Handles subscribe button click
23  handleSubscribe() {
24    // Callback invoked whenever a new event message is received
25    const messageCallback = function (response) {
26      console.log("New message received: ", JSON.stringify(response));
27      // Response contains the payload of the new message received
28    };
29
30    // Invoke subscribe method of empApi. Pass reference to messageCallback
31    subscribe(this.channelName, -1, messageCallback).then((response) => {
32      // Response contains the subscription information on subscribe call
33      console.log("Subscription request sent to: ", JSON.stringify(response.channel));
34      this.subscription = response;
35      this.toggleSubscribeButton(true);
36    });
37  }
38
39  // Handles unsubscribe button click
40  handleUnsubscribe() {
41    this.toggleSubscribeButton(false);
42
43    // Invoke unsubscribe method of empApi
44    unsubscribe(this.subscription, (response) => {
45      console.log("unsubscribe() response: ", JSON.stringify(response));
46      // Response is true for successful unsubscribe
47    });
48  }
49
50  toggleSubscribeButton(enableSubscribe) {
51    this.isSubscribeDisabled = enableSubscribe;
52    this.isUnsubscribeDisabled = !enableSubscribe;
53  }
54
55  registerErrorListener() {
56    // Invoke onError empApi method
57    onError((error) => {
58      console.log("Received error from server: ", JSON.stringify(error));
59      // Error contains the server-side error
60    });
61  }
62}

Usage Considerations 

The lightning/empApi module is supported in desktop browsers with web worker or shared worker support. It is not supported in the Salesforce mobile app. For more information about web workers and browser support, see the Web Workers W3C specification and Using Web Workers in the Mozilla Developer Network documentation.

You can use the lightning/empApi module only on the main window of a page. You can’t use the lightning/empApi module on a child window. For example, in a screen flow, you can use the lightning/empApi module only on the main screen but not on a button in a screen flow. Similarly, you can’t use the lightning/empApi module in the utility bar pop-out window. Another example is a Visualforce page that contains a top-level window and child iframe windows. In this case, the lightning/empApi module must be on the top-level window.

See Also 

error fallback image
No specifications to show
No specifications are available for this component or API module. When specifications are defined, they'll appear here.