Salesforce Platform Event: Implementing Publish and Subscribe with Apex Code Events


11/03/2024


 

Welcome to the future of Salesforce development – where real-time communication, seamless integration, and unparalleled efficiency converge. In today's digital era, businesses demand agile solutions that can adapt and respond instantaneously to changing circumstances. That's where Salesforce Platform Events come into play, revolutionizing the way we build, connect, and innovate on the Salesforce platform.

This blog post provides a comprehensive overview of implementing publish and subscribe with Apex code events in Salesforce.

 

After completing this unit, you will able to:

1. What is  Platform Events in Salesforce?

2.  Create Platform Events in Salesforce

3. Implementing Publish and Subscribe with Apex Code Events

4. Test the Platform Event


1.  What is  Platform Events in Salesforce?

Platform Events provide a robust and flexible framework for broadcasting event notifications within the Salesforce ecosystem. Whether it's a new lead being created, an opportunity reaching a critical stage, or a customer updating their information, Platform Events empower developers to trigger actions and processes in real-time, ensuring that your Salesforce org remains synchronized and responsive to every interaction.

Platform Events allow different components, such as triggers, processes, or external systems, to communicate with each other asynchronously. This means that rather than relying solely on the traditional request-response model, where actions are triggered by user interactions or scheduled processes, events can be published to a central event bus and subscribed to by interested parties.


2.  Create Platform Events in Salesforce

1. Go to Setup and search for Platform Events.

2. Click New Platform Event.

3. Define the event name, API name, and custom fields that will carry the data you want to send.

4. Choose the Publish Behavior (default is "Publish After Commit").

5. Save the platform event.

Now we will create the fields on this platform event. Here are the fields details:

Field Name Data Type
Name Text(255)
Rating Text(255)
Status Text(255)
Type Text(255)
Website Text(255)

 

3. Implementing Publish and Subscribe with Apex Code Events

Publishing events involves creating an instance of the custom event class and then firing the event using the EventBus.publish() method. Any subscribers listening for this event will be notified.

In Salesforce development, platform events offer a robust mechanism for implementing publish and subscribe patterns, facilitating real-time communication between different components of your Salesforce organization. Apex triggers provide a powerful means to both publish and subscribe to platform events, allowing developers to build event-driven architectures efficiently. In this article, we'll delve into how to implement both publishing and subscribing to platform events using an Apex trigger.

Publishing platform events involves creating instances of the event object and inserting them into Salesforce using DML operations. This can be achieved within Apex code, allowing you to trigger events based on certain conditions or user actions.

Here are the apex class:

public class MyPlatformEvent {
    public static void publishEvent() {
        List<My_Platform_Event__e> myPlatformEvents = new List<My_Platform_Event__e>();
        My_Platform_Event__e event = new My_Platform_Event__e(Name__c = 'Test', Rating__c = 'Hot', Status__c = 'Active', Type__c = 'Customer - Direct', Website__c = 'https://www.google.com/');
        myPlatformEvents.add(event);
        List<Database.SaveResult> results = EventBus.publish(myPlatformEvents);
        for (Database.SaveResult sr: results) {
            if (sr.isSuccess()) {
                System.debug('Successfully published event.');
            } else {
                for(Database.Error err: sr.getErrors()) {
                    System.debug('Error returned: ' + err.getStatusCode() + ' - ' + err.getMessage());
                }
            }      
        }
    }
}

Subscribing to platform events entails creating an Apex trigger that listens for the occurrences of the platform event. Within the trigger, define the logic to handle the event and perform necessary actions based on the event data.

Here are the apex trigger:

trigger myPlatformEventTrigger on My_Platform_Event__e (after insert) {
    for(My_Platform_Event__e event: Trigger.New) {
        System.debug('Event Data: '+event);
    }
}
 

4. Test the Platform Event

Testing platform events in Salesforce is essential to ensure the reliability and functionality of your event-driven architecture. By thoroughly testing the publication and subscription of platform events, developers can verify that events are being triggered and processed correctly.

This involves invoking the method or trigger responsible for publishing the event like this:

MyPlatformEvent.publishEvent();

Including debug statements in your platform event testing helps provide visibility into the execution flow and aids in troubleshooting any issues that may arise. These debug statements provide insights into various stages of the testing process, such as publishing the platform event, asserting its publication, and handling the event in the trigger. They can be invaluable in diagnosing any unexpected behavior or errors encountered during testing.

So make sure the debug statement is successfully logged in the debug logs from setup like the below figure:



Note: If you can't see the debug statement for the platform event, make sure you have enabled the debug log for Automated Process from setup like the below figure: