How can developers utilize Platform Events and LWC to power real-time dashboard data updates without refreshing?
Answer
Basics: Standard dashboards and reports refresh on a schedule or manual action. For live operations screens (queue depth, order status), the server should push changes. Platform events are Salesforce's publish/subscribe messages and empApi lets a Lightning component listen to them.
How it works:
- Define a platform event (
Metric_Update__e) with fields such asMetric_Name__candValue__c. - Publish from Apex (
EventBus.publish), Flow ("Create Records" on the event object), or an external system through REST. - In the LWC, import
subscribe,unsubscribe,onErrorfromlightning/empApi, subscribe to/event/Metric_Update__einconnectedCallback, and update tracked state in the callback. - Unsubscribe in
disconnectedCallback. - Users need Read access to the event object.
Advanced / deep dive: For record-change dashboards, Change Data Capture channels (/data/AccountChangeEvent) avoid custom publishing code. Push small deltas or just record IDs and then call refreshApex on a wired method so data respects sharing. Throttle UI updates (debounce) when events arrive rapidly. Event delivery is not exactly-once and the dashboard may reconnect and miss events, so on reconnect do a full refresh query. Streaming client allocations and daily event delivery limits depend on edition (verify). empApi is for Lightning Experience; support in Experience Cloud/LWR and mobile has restrictions, so check docs or fall back to polling.
Code / config example:
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
export default class LiveMetrics extends LightningElement {
channel = '/event/Metric_Update__e';
subscription = null;
metrics = {};
connectedCallback() {
onError(err => console.error('empApi error', JSON.stringify(err)));
subscribe(this.channel, -1, msg => {
const p = msg.data.payload;
this.metrics = { ...this.metrics, [p.Metric_Name__c]: p.Value__c };
}).then(resp => { this.subscription = resp; });
}
disconnectedCallback() {
if (this.subscription) unsubscribe(this.subscription, () => {});
}
}
Hidden gotchas & must-remember points:
- Always unsubscribe, or listeners leak.
- Platform events ignore sharing; do not push sensitive data.
- Replay
-1means only events after subscription; do an initial data load separately. - There is no guaranteed delivery on a closed tab; refresh on load.
empApidoes not work in all contexts (e.g., certain Experience Cloud setups).- Publishing counts against event publishing allocations.
Best practice: Load initial state with wire/Apex, then apply pushed deltas, and refresh fully on reconnect.