Sub topic 4
Publishing events from Apex
This chapter assumes you can write Apex classes and triggers, you know how DML and transactions work, and you have already defined a platform event such as Order_Shipped__e with the custom fields Order_Number__c and Status__c.
How EventBus.publish works
EventBus.publish sends platform events to the event bus. It accepts a single event, or a list of events, and returns a Database.SaveResult (or a list of them). Each result tells you whether Salesforce accepted that event for publishing.
Publishing is not the same as delivery. A successful result means the event was accepted. Subscribers receive it afterward, in a separate process.
Order_Shipped__e evt = new Order_Shipped__e(
Order_Number__c = '00012345',
Status__c = 'Shipped'
);
Database.SaveResult sr = EventBus.publish(evt);
if (!sr.isSuccess()) {
for (Database.Error err : sr.getErrors()) {
System.debug('Publish failed: ' + err.getStatusCode() + ' ' + err.getMessage());
}
}The code does three things:
- It creates the event as an sObject with
new. The event type is the API name ending in__e. - It calls
EventBus.publish(evt). - It checks
isSuccess()and reads eachDatabase.Errorfor the status code and message.
Publish behavior and the result
The publish behavior you chose on the event definition changes when the event leaves your transaction.
| Publish behavior | When the event is published |
|---|---|
| Publish After Commit | After the publishing transaction commits. |
| Publish Immediately | As soon as `EventBus.publish` is called. |
With Publish After Commit, a rollback means the event is never published. With Publish Immediately, the event is published even if the transaction later rolls back, so a subscriber can see an event for work that never saved.
Publishing in bulk
Pass a list to publish many events in one call. This uses one DML-style call instead of one per event, which matters because each EventBus.publish call counts against governor limits.
List<Order_Shipped__e> events = new List<Order_Shipped__e>();
for (Order o : [SELECT OrderNumber FROM Order WHERE Status = 'Shipped']) {
events.add(new Order_Shipped__e(
Order_Number__c = o.OrderNumber,
Status__c = 'Shipped'
));
}
List<Database.SaveResult> results = EventBus.publish(events);
for (Database.SaveResult sr : results) {
if (!sr.isSuccess()) {
System.debug('Publish failed: ' + sr.getErrors()[0].getMessage());
}
}Common errors
- Ignoring the result.
EventBus.publishdoes not throw when an event is rejected. It reports the failure in theSaveResult. If you never checkisSuccess(), failures pass silently. - Assuming a query can find the event. Platform events are not stored like records, so you cannot read them back with SOQL.
- Publishing inside a loop. Calling
EventBus.publishonce per iteration can exceed limits. Collect events into a list and publish once. - Expecting a rollback to cancel the event. This holds only for Publish After Commit.
Exercise
A trigger publishes an event with EventBus.publish, then a later validation error rolls back the transaction. The event definition uses Publish After Commit. Is the event delivered to subscribers? What changes if the definition uses Publish Immediately?
Show answer
With Publish After Commit, the event is not published, because the transaction never commits. With Publish Immediately, the event is published at the call to EventBus.publish, so subscribers still receive it even though the transaction rolled back.
Exercise
Why should you check isSuccess() on the SaveResult after publishing, and why should you publish a list of events instead of calling EventBus.publish inside a loop?
Show answer
EventBus.publish reports rejected events through the SaveResult instead of throwing an exception, so unchecked failures go unnoticed. Publishing a list makes one call instead of many, which stays within governor limits.