How do Apex developers publish Platform Event messages programmatically using the EventBus class?
Answer
Basics: Platform events are messages on a Salesforce event bus. The publisher creates an instance of the event type (an sObject whose API name ends in __e) and publishes it, and any subscribed Apex trigger, Flow, LWC or external client receives it. Publishing is a fire-and-forget step, so the publisher does not wait for subscribers.
How it works:
- Define the event (Setup > Platform Events), with its fields and its Publish Behavior.
- Build instances in Apex with
new Order_Event__e(...). - Call
EventBus.publish(list). Each element returns aSaveResult. - Check
isSuccess()and readgetErrors()for problems such as a missing required field. - The bus stores the event and delivers it to subscribers asynchronously.
Advanced / deep dive: Publishing counts as one DML statement per call, so batch events into a list. It also counts against the hourly event publishing allocation for the org (verify the current figure for your edition). Publish Behavior decides whether the event goes out immediately or only after the transaction commits. A successful result for an after-commit event only means it is queued until the commit. Publishing is also possible through REST, Pub/Sub API and Flow (Create Records on an event object). In tests, publish between Test.startTest() and Test.stopTest() and call Test.getEventBus().deliver() to force delivery.
Code / config example:
public with sharing class OrderEventPublisher {
{
List<Order_Event__e> events = <Order_Event__e>();
(Order o : orders) {
events.add( (Order_Id__c = o.Id, Status__c = o.Status));
}
List<Database.SaveResult> results = EventBus.publish(events);
(Database.SaveResult sr : results) {
(!sr.isSuccess()) {
(Database.Error err : sr.getErrors()) {
System.debug(LoggingLevel.ERROR, err.getStatusCode() + + err.getMessage());
}
}
}
}
}