How to subscribe to a Platform Event using Trigger

Let's look at how to subscribe to Platform Events using Triggers.

We can fire a Platform Event from Process Builder, Flow, Apex, and API.

Likewise we can also subscribe to the Platform Event using Process Builder, Flows, Apex Triggers, Lightning Components, and Comet D.

In this blog post am gonna walk you through how can we subscribe to the Platform Event using an Apex Trigger.

Before we look into this example we need to make sure that the Platform Event is created.

Just like how we have the API name of the custom object ending with __c for a Platform Event the API name ends with __e.

Before you use the snippet, create a Platform event with the fields mentioned in the below Trigger.

Now am gonna use that API name and write a Trigger on that, hence in the below snippet you will find the API name of the Platform Event where we usually specify the Sobject name.

trigger OrderEventTrigger on Order_Event__e (after insert) {    
    
    //loop through all the records in the list
    for (Order_Event__e event : Trigger.New) {
    	//debug fields of the platform event
		System.debug(' 🚀 ' + event.Account_Id__c );
		System.debug(' 🚀 ' + event.Amount__c );
		System.debug(' 🚀 ' + event.Opportunity_Id__c );        
    }
    
}

To check the logs you also need to create a New Trace Flag for the Automated Process user.

Follow these steps to create a Track Flag for Automated Process user.

  1. Navigate to Setup
  2. In Quick Find search for Debug Logs
  3. Click on the new button
  4. For Traced Entity Type the value should be Automated Process
  5. Provide the other values for the fields

Now you can fire the Platform Event and in the debug logs you will find the entries.

Hope this was helpful!