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.