# How do you subscribe to Platform Events and streaming channels in LWC using lightning/empApi?

**Topic:** LWC · **Difficulty:** Medium · **Tags:** LWC, empApi, Platform Events

Read it on the site: https://www.forcechallenges.com/interview-questions/how-do-you-subscribe-to-platform-events-and-streaming-channels-in-lwc-using-lightning-empapi

## Answer

**Basics:** Instead of polling, a component subscribes to a channel and a callback runs whenever an event is published. Channel names: platform events `/event/Order_Update__e`, CDC `/data/AccountChangeEvent`, PushTopic `/topic/MyTopic`, generic streaming `/u/ChannelName`. The user needs read access to the event or object.

**How it works:** Import `subscribe`, `unsubscribe`, `onError`, and optionally `setDebugFlag`, `isEmpEnabled`. `subscribe(channel, replayId, callback)` returns a Promise resolving to a subscription object. `replayId` `-1` means new events only, `-2` means all retained events. The callback receives a message with `message.data.payload` for platform events and CDC. Store the subscription, and call `unsubscribe(subscription, cb)` in `disconnectedCallback`.

**Advanced / deep dive:** Retained events can be replayed for 72 hours (platform events and CDC; verify in current release notes since the window and per-edition event allocations are product and version dependent). Delivery is at-least-once and not strictly guaranteed to be ordered with respect to your UI, so make handlers idempotent and track the last `replayId` if you need gap recovery. Streaming concurrent client limits and 24-hour event delivery allocations are edition-based and enforced per org; many open components each hold a CometD subscription, so avoid subscribing in every row component. Publish from Apex with `EventBus.publish` (note that "publish after commit" versus "publish immediately" behavior depends on the event definition). For high volume, use the Pub/Sub API with an external subscriber rather than the browser. Security: events do not enforce record-level sharing beyond object permissions for platform events (they are not records), so do not leak sensitive data in payloads; CDC respects field access and sharing for the subscribing user.

**Code / config example:**
```javascript
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';

export default class OrderFeed extends LightningElement {
    channel = '/event/Order_Update__e';
    subscription = null;

    connectedCallback() {
        onError(err => console.error('empApi error', JSON.stringify(err)));
        subscribe(this.channel, -1, (msg) => {
            const p = msg.data.payload;
            this.latest = p.Order_Number__c;
        }).then(sub => { this.subscription = sub; });
    }
    disconnectedCallback() {
        if (this.subscription) unsubscribe(this.subscription, () => {});
    }
}
```

**Hidden gotchas & must-remember points:**
- Unsubscribe in `disconnectedCallback`, or listeners and client slots leak.
- `-1` misses events published while the component was not loaded; `-2` replays all retained events.
- Payload field names carry the `__c` suffix for custom fields.
- It works in Lightning Experience and supported site types; verify support for your container.
- Concurrent subscriber and daily delivery limits exist by edition.
- It is for UI notification, not guaranteed-delivery integration.

**Best practice:** Subscribe once per page (in a container component or service), unsubscribe on teardown, and treat payloads as triggers to refresh rather than as the sole source of truth.

---
Source: ForceChallenges · last updated 2026-11-02
