Sub topic 8
Subscribing from Lightning components and external clients
This chapter assumes you know what a change event is, how channel names like /data/AccountChangeEvent are formed, and basic JavaScript. Apex triggers are one kind of subscriber. This chapter covers the other kinds, which receive events outside the Salesforce transaction.
Choosing a subscriber
Three client options exist. Pick by where the code runs.
| Option | Runs in | Protocol | Notes |
|---|---|---|---|
| `lightning/empApi` | Lightning web components and Aura | CometD, wrapped by Salesforce | No separate login. Uses the user's session. |
| CometD client | External system | Bayeux over long polling | Older option. You manage the handshake and the session token. |
| Pub/Sub API | External system | gRPC | Current option for new integrations. You manage a replay ID and the schema. |
For a new external integration, prefer Pub/Sub API. Use empApi when the consumer is a component that updates the screen.
How a subscription works
A client names a channel and a replay position. The event bus then pushes each event to the client as it is published. The client does not poll.
Subscribing from a Lightning web component
The lightning/empApi module exposes subscribe, unsubscribe, and onError. The example below listens for Account changes.
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
export default class AccountChangeListener extends LightningElement {
subscription = null;
channelName = '/data/AccountChangeEvent';
connectedCallback() {
onError((error) => {
console.error('empApi error', JSON.stringify(error));
});
subscribe(this.channelName, -1, (message) => {
const header = message.data.payload.ChangeEventHeader;
console.log(header.changeType, header.recordIds);
}).then((response) => {
this.subscription = response;
});
}
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription, () => {});
}
}
}Points to notice:
- The second argument to
subscribeis the replay ID.-1means only events published after the subscription starts.-2means all events still in the retention window. - The callback receives the event under
message.data.payload. The header is nested inside it. disconnectedCallbackunsubscribes. Without it, a component that is removed keeps a live subscription.
Subscribing from an external client
An external client has to handle authentication, connection, and recovery itself. The steps are the same for CometD and Pub/Sub API:
- Authenticate with an OAuth flow and get an access token.
- Connect to the endpoint for your org.
- Subscribe to the channel with a replay ID.
- Process each event, then store its replay ID.
- On reconnect, subscribe again with the last stored replay ID.
Step 4 is where reliability comes from. Store the replay ID only after your processing succeeds. If you store it first and then crash, the event is lost. If you store it after, a crash causes a repeat delivery, so make processing safe to run twice.
Pub/Sub API also delivers events in Avro format. Fetch the schema by its ID and decode each payload with it. CometD delivers JSON.
Exercise
An external client stores the replay ID of each event before it processes the event. The client crashes halfway through processing event 41. After restart, it subscribes with the stored ID 41. What goes wrong, and how do you fix it?
Show answer
The client resumes after event 41, so event 41 is never fully processed and is lost. Store the replay ID only after processing succeeds. Because a crash can then cause event 41 to be delivered again, make the processing idempotent, so a repeat has no extra effect.
Exercise
A component subscribes with replay ID -2 and shows a flood of old changes on load. Which value avoids this, and what does it change?
Show answer
Use -1. It delivers only events published after the subscription starts, instead of everything in the retention window.