Newer Version Available

This content describes an older version of this product. View Latest

Publish Event Messages with Apex

Use Apex to publish event messages from a Salesforce app.

To publish event messages, call the EventBus.publish method. For example, if you’ve defined a custom platform event called Low Ink, reference this event type as Low_Ink__e. Next create instances of this event and pass them to the Apex method.

Example

This example creates two events of type Low_Ink__e, publishes them, and then checks whether the publishing was successful or errors were encountered.

Before you can run this snippet, define a platform event with the name of Low_Ink__e and the following fields: Printer_Model__c of type Text, Serial_Number__c of type Text (marked as required), Ink_Percentage__c of type Number(16, 2).

1List<Low_Ink__e> inkEvents = new List<Low_Ink__e>();
2inkEvents.add(new Low_Ink__e(Printer_Model__c='XZO-5', Serial_Number__c='12345', 
3              Ink_Percentage__c=0.2));
4inkEvents.add(new Low_Ink__e(Printer_Model__c='MN-123', Serial_Number__c='10013', 
5              Ink_Percentage__c=0.15));
6
7
8// Call method to publish events
9List<Database.SaveResult> results = EventBus.publish(inkEvents);
10
11// Inspect publishing result for each event
12for (Database.SaveResult sr : results) {
13    if (sr.isSuccess()) {
14        System.debug('Successfully published event.');
15    } else {
16        for(Database.Error err : sr.getErrors()) {
17            System.debug('Error returned: ' +
18                        err.getStatusCode() +
19                        ' - ' +
20                        err.getMessage());
21        }
22    }       
23}

For each event, Database.SaveResult contains information about whether the operation was successful and the errors encountered. If the isSuccess() method returns true, the event was published for a standard-volume event. For a high-volume event, the publish request is queued in Salesforce and the event message might not be published immediately. For more information, see High-Volume Platform Event Persistence. If isSuccess() returns false, the event publish operation resulted in errors which are returned in the Database.Error object. EventBus.publish() can publish some passed-in events, even when other events can’t be published due to errors. The EventBus.publish() method doesn’t throw exceptions caused by an unsuccessful publish operation. It is similar in behavior to the Apex Database.insert method when called with the partial success option.

Database.SaveResult also contains the Id system field. The Id field value is not included in the event message delivered to subscribers. It is not used to identify an event message, and is not always unique.

The event insertion occurs non-transactionally. As a result, you can’t roll back published events. Because event publishing is equivalent to a DML insert operation, DML limits and other Apex governor limits apply.