Sub topic 2
Publishing and Subscribing to Salesforce Platform Events
Assume you know basic Flow, Apex triggers, Lightning Web Components (LWC), REST, and Salesforce transactions. A platform event is a message with a defined schema. A publisher sends it to the event bus. Subscribers receive it independently.
Publishing events from Flow
In Flow, add a Create Records element after the business action that should produce the event. Select the platform event object, such as Order_Shipped__e, and map values to its custom fields. The event is then published when the flow transaction publishes it.
Use publish after commit when subscribers must see only successfully committed data. Use publish immediately only when subscribers must receive the event even if the surrounding transaction later fails.
Publishing through the REST API
An external application can publish an event through the standard sObject REST endpoint:
POST /services/data/v60.0/sobjects/Order_Shipped__e/
Authorization: Bearer <access_token>
Content-Type: application/json
{
"Order_Number__c": "00012345",
"Status__c": "Shipped"
}The caller needs Salesforce authentication and permission to create the platform event.
Subscribing with an Apex trigger
A platform event trigger runs only with after insert. Salesforce supplies delivered events in Trigger.new. Process the batch, and keep the logic bulk-safe.
trigger OrderShippedTrigger on Order_Shipped__e (after insert) {
List<Task> tasks = new List<Task>();
for (Order_Shipped__e evt : Trigger.new) {
tasks.add(new Task(
Subject = 'Follow up on order ' + evt.Order_Number__c,
Status = 'Not Started'
));
}
insert tasks;
}Subscribing with a platform event-triggered Flow
Create a flow whose trigger is A platform event. Select Order_Shipped__e, then add actions such as Get Records, Decision, and Create Records. The flow runs once for each delivered event and can update Salesforce data without a user interface.
Subscribing in an LWC with empApi
The lightning/empApi module subscribes to an event channel. Replay ID -1 requests new events only.
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe } from 'lightning/empApi';
export default class OrderShippedListener extends LightningElement {
subscription;
connectedCallback() {
subscribe('/event/Order_Shipped__e', -1, message => {
console.log(message.data.payload.Order_Number__c);
}).then(result => {
this.subscription = result;
});
}
disconnectedCallback() {
if (this.subscription) unsubscribe(this.subscription, () => {});
}
}Exercise
Which subscriber should you choose for creating Salesforce records in response to every event?
Show answer
Use an Apex trigger or a platform event-triggered Flow. Use an LWC when the response belongs in a browser interface.