Newer Version Available
Subscribe to Platform Event Notifications with Apex Triggers
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}