Emp API

lightning:empApi

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

For Aura components only. For LWC development, use lightning-emp-api.

For Use In

Lightning Experience

The lightning:empApi component 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 component 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 component only supports one user per browser. Multiple user sessions aren’t supported in one browser.

To call the component’s methods, add the lightning:empApi component inside your custom component and assign an aura:id attribute to it.

1<lightning:empApi aura:id="empApi"/>

This example subscribes to a channel when you click the Subscribe button. The channel is specified in an input component. The default value provided is an example platform event channel. Replace the value with the desired channel name. A callback function on the subscribe() call prints the payload of each received event to the console. To view the event messages, enable your browser console view. The Unsubscribe button lets you stop the subscription and stop receiving event notifications.

1<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
2    <!-- EMP API component -->
3    <lightning:empApi aura:id="empApi" />
4
5    <!-- Calls the onInit controller function on component initalization -->
6    <aura:handler name="init" value="{!this}" action="{!c.onInit}"/>
7
8    <!-- Holds the streaming event subscription -->
9    <aura:attribute name="subscription" type="Map" />
10
11    <!-- Form for subscribing/unsubscribing to/from events -->
12    <lightning:input aura:id="channel" label="channel" name="channel" type="text" value="/event/Test__e"/>
13    <lightning:button label="Subscribe" onclick="{! c.subscribe }" />
14    <lightning:button label="Unsubscribe" onclick="{! c.unsubscribe }" disabled="{!empty(v.subscription)}"/>
15</aura:component>

Add the following client-side controller functions. They are called by the Subscribe and Unsubscribe buttons. Each controller function calls the corresponding subscribe or unsubscribe method on the empApi component.

1({
2  // Sets an empApi error handler on component initialization
3  onInit: function (component, event, helper) {
4    // Get the empApi component
5    const empApi = component.find("empApi");
6
7    // Uncomment below line to enable debug logging (optional)
8    // empApi.setDebugFlag(true);
9
10    // Register error listener and pass in the error handler function
11    empApi.onError(
12      $A.getCallback((error) => {
13        // Error can be any type of error (subscribe, unsubscribe...)
14        console.error("EMP API error: ", JSON.stringify(error));
15      }),
16    );
17  },
18
19  // Invokes the subscribe method on the empApi component
20  subscribe: function (component, event, helper) {
21    // Get the empApi component
22    const empApi = component.find("empApi");
23    // Get the channel from the input box
24    const channel = component.find("channel").get("v.value");
25    // Replay option to get new events
26    const replayId = -1;
27
28    // Subscribe to an event
29    empApi
30      .subscribe(
31        channel,
32        replayId,
33        $A.getCallback((eventReceived) => {
34          // Process event (this is called each time we receive an event)
35          console.log("Received event ", JSON.stringify(eventReceived));
36        }),
37      )
38      .then((subscription) => {
39        // Subscription response received.
40        // We haven't received an event yet.
41        console.log("Subscription request sent to: ", subscription.channel);
42        // Save subscription to unsubscribe later
43        component.set("v.subscription", subscription);
44      });
45  },
46
47  // Invokes the unsubscribe method on the empApi component
48  unsubscribe: function (component, event, helper) {
49    // Get the empApi component
50    const empApi = component.find("empApi");
51    // Get the subscription that we saved when subscribing
52    const subscription = component.get("v.subscription");
53
54    // Unsubscribe from event
55    empApi.unsubscribe(
56      subscription,
57      $A.getCallback((unsubscribed) => {
58        // Confirm that we have unsubscribed from the event channel
59        console.log("Unsubscribed from channel " + unsubscribed.subscription);
60        component.set("v.subscription", null);
61      }),
62    );
63  },
64});

Usage Considerations 

The lightning:empApi component is supported only 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 add the lightning:empApi component only on the main window of a page. You can’t add the lightning:empApi component on a child window. For example, in a screen flow, you can add the lightning:empApi component only on the main screen but not on a button in a screen flow. Similarly, you can’t add the lightning:empApi component 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 component must be on the top-level window.

See Also 

Attributes 

NameDescriptionTypeDefaultRequired
bodyThe body of the component. In markup, this is everything in the body of the tag.Aura.Component[]

Methods 

NameDescriptionArgument NameArgument TypeArgument Description
isEmpEnabledReturns 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.
onErrorRegisters a listener to errors that the server returns.callbackFunctionA callback function that's called when an error response is received from the server for handshake, connect, subscribe, and unsubscribe meta channels.
setDebugFlagTurns console logging on or off.flagBooleanSet to true or false to turn console logging on or off respectively.
subscribeSubscribes to a given channel and returns a promise that holds a subscription object, which you use to unsubscribe later.channelStringThe channel name to subscribe to.
replayIdLongIndicates 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.
unsubscribeUnsubscribes 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 https://docs.cometd.org/current3/reference/#_bayeux_meta_unsubscribe.subscriptionObjectSubscription object that the subscribe call returned.
callbackFunctionA callback function that's called with a server response for the unsubscribe call.