Sub topic 9
Subscribing in a Lightning Web Component with empApi
This chapter shows how a Lightning Web Component (LWC) listens for platform events in the browser. It assumes you can write a basic LWC with lifecycle hooks, and that the Order_Shipped__e event from earlier chapters exists with the fields Order_Number__c and Status__c.
The working model
The lightning/empApi module is a client for the event bus, built on the streaming API. When a component subscribes to a channel, the browser keeps a long-lived connection open. Each delivered event arrives as a message object, and your callback runs once per message.
The channel name for a platform event is /event/ followed by the event API name. For Order_Shipped__e, the channel is /event/Order_Shipped__e.
The three functions
The module exports three functions that this chapter uses.
subscribe(channel, replayId, callback)opens the subscription. It returns a promise that resolves to a subscription object.unsubscribe(subscription, callback)closes the subscription.onError(callback)registers a handler for errors from the connection.
The replay ID tells the bus where to start. The value -1 means "only events published after I subscribe." The value -2 means "everything still in the retention window." A specific ID means "everything after that event." The next chapter covers replay in detail.
A complete component
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
export default class OrderShippedListener extends LightningElement {
channelName = '/event/Order_Shipped__e';
subscription = null;
connectedCallback() {
onError((error) => {
console.error('empApi error', JSON.stringify(error));
});
subscribe(this.channelName, -1, (message) => {
const payload = message.data.payload;
console.log('Order shipped: ' + payload.Order_Number__c);
}).then((response) => {
this.subscription = response;
});
}
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription, () => {});
}
}
}Here is how it works:
connectedCallbackruns when the component is inserted into the page. It registers the error handler and subscribes.- The callback receives a message. The field values are in
message.data.payload, keyed by API name. Other useful values aremessage.data.event.replayIdandmessage.data.schema. - The promise returns the subscription object. The component stores it so it can unsubscribe later.
disconnectedCallbackruns when the component is removed. Unsubscribing here stops the component from holding a connection and receiving events it can no longer show.
Showing the data
Logging to the console proves the subscription works, but a real component updates its state. Assign the payload to a tracked field or a plain class field, and the template re-renders. Keep the callback short. It runs on the browser's main thread, so heavy work there slows the page.
Common errors
| Symptom | Likely cause |
|---|---|
| No messages arrive | The channel name is wrong, or the event API name lacks the `__e` suffix. |
| Only new events appear after a refresh | The replay ID is `-1`. Use `-2` to see retained events, if that is what you need. |
| Duplicate callbacks | The component subscribed more than once, often because it was never unsubscribed after being removed and re-added. |
| `payload` fields are `undefined` | The field name does not match the API name, including the `__c` suffix and its case. |
| The subscription stops after a long idle time | The connection dropped. Handle this in `onError` and subscribe again if needed. |
Exercise
A component subscribes with replay ID -1 to /event/Order_Shipped__e. An event is published, then the user opens the page. Does the component receive that event? What would you change if you wanted it to, and what must also be true for it to work?
Show answer
No. The replay ID -1 delivers only events published after the subscription starts. Change the replay ID to -2 to receive all events still in the retention window, or to a stored replay ID to receive events after that point. The event must still be within the retention window, because the bus keeps events only for a limited time.
Exercise
Why should the component call unsubscribe in disconnectedCallback, and what is the visible symptom if it does not?
Show answer
Without unsubscribe, the subscription stays open after the component is removed. If the component is added again, it subscribes a second time, so the callback can run twice for each event, producing duplicate output or duplicate work.