Publish/Subscribe a Platform Event Using Apex Code and Apex Triggers

Publish a Platform Event Using Apex Code

To publish event messages, you create an instance of the event and pass it to the EventBus.publish() method.

Subscribe a Platform Event Using Apex Trigger

You simply write an after insert Apex trigger on the event object to subscribe to incoming events. Triggers provide an autosubscription mechanism in Apex.

Platform events support only after insert triggers. After an event message is published, the after insert trigger is fired.

Problem Statement

When an Account is updated with Customer Priority Field as high, update the priority field related case records with same value. However, the last modified by of those updated case record should not be the one who modified the account record.

Important Notes

Order of Event Processing

A trigger processes platform event notifications sequentially in the order they’re received. The order of events is based on the event replay ID.

Asynchronous Trigger Execution

A platform event trigger runs in its own process asynchronously and isn’t part of the transaction that published the event.

There might be a delay between when an event is published and when the trigger processes the event.

Automated Process System User

Platform event triggers don’t run under the user who executes them (the running user) but under the Automated Process system user

Please refer below video for detailed explainaion with example :

Leave a comment