Newer Version Available

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

Subscribe to Platform Event Notifications with Apex Triggers

Use Apex triggers to subscribe to events. You can receive event notifications in triggers regardless of how they were published—through Apex or APIs. Triggers provide an autosubscription mechanism. No need to explicitly create and listen to a channel in Apex.

An Apex trigger processes platform event notifications sequentially in the order they’re received. The order of events is based on the event replay ID. An Apex trigger can receive a batch of events at once. In this case, the order of events is preserved within each batch.

To subscribe to event notifications, write an after insert trigger on the event object type. The after insert trigger event corresponds to the time after a platform event is published. After an event message is published, the after insert trigger is fired.

This example shows a trigger for the Low Ink event. It iterates through each event and checks a field value. The trigger inspects each received notification and gets the printer model from the notification. If the printer model matches a certain value, other business logic is executed. For example, the trigger creates a case to order a new cartridge for this printer model.

1// Trigger for catching Low_Ink events.
2trigger LowInkTrigger on Low_Ink__e (after insert) {    
3    // List to hold all cases to be created.
4    List<Case> cases = new List<Case>();
5    
6    // Get user Id for case owner
7    User usr = [SELECT Id FROM User WHERE Name='Admin User' LIMIT 1];
8       
9    // Iterate through each notification.
10    for (Low_Ink__e event : Trigger.New) {
11        System.debug('Printer model: ' + event.Printer_Model__c);
12        if (event.Printer_Model__c == 'MN-123') {
13            // Create Case to order new printer cartridge.
14            Case cs = new Case();
15            cs.Priority = 'Medium';
16            cs.Subject = 'Order new ink cartridge for SN ' + event.Serial_Number__c;
17            cs.OwnerId = usr.Id;
18            cases.add(cs);
19        }
20   	}
21    
22    // Insert all cases corresponding to events received.
23    insert cases;
24}

If you create a Salesforce record with an ownerId field in the trigger, explicitly set the owner ID. For cases and leads, you can alternatively use assignment rules to set the owner. See Apex, API, and SOQL Considerations for Platform Events.

Note