Newer Version Available
Publish Event Messages with Apex
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. The example assumes that the Low Ink platform event is defined in your org.
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}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.