Platform Events

Shama Gurav
3 min readJan 23, 2024

--

Platform event is a built in feature of salesforce which provides an event-driven messaging architecture and follow pub/sub model for transfer of information. The platform events get published on event bus and then can be delivered to its subscribers in chronological order.

Platform events enable apps to communicate inside and outside salesforce.

Use Case 1: Communicating inside salesforce using platform events:

If the account source is changed from UI then display a warning message.

Solution:

  1. Create a platform event ‘AccountSourceChanged’ with custom field message.

2. Create custom component (LWC or AURA) to display warning message and subscribe to platform event created on step 1.

showwarning.cmp

<aura:component  implements="flexipage:availableForRecordHome,force:hasRecordId,force:appHostable" access="global" >
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />

<lightning:empApi aura:id="empApi" />
</aura:component>

showwarningcontroller.js

({
doInit : function(component, event, helper) {
const empApi = component.find("empApi");
var channel = '/event/AccountSourceChanged__e';

const replayId = -1;

console.log('###### ' + empApi);
//A callback function that's invoked for every event received
const callback = function (message) {
var msg = message.data.payload;

if(!(msg=== undefined || msg ==null))
{

var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
title : 'Warning',
message: msg.Message__c,
duration:' 5000',
key: 'info_alt',
type: 'warning',
mode: 'sticky'
});
toastEvent.fire();
}


};
// Subscribe to the channel and save the returned subscription object.
empApi.subscribe(channel, replayId, callback).then(function(newSubscription) {

});
const errorHandler = function (message) {
console.error("Received error ", JSON.stringify(message));
};
//A callback function that's called when an error response is received from the server for the handshake, connect, subscribe, and unsubscribe meta channels.
empApi.onError(errorHandler);

},

})
  1. If account source changes then publish platform event using flow or trigger. Implement the custom component (LWC or AURA) which will subscribe the event and will show the notification when event is delivered.
  2. Below is the code to publish event from account trigger if source of account is changed,
trigger AccTrigger on Account (after update) {
if(trigger.isafter )
{
if(trigger.isUpdate)
{
AccountSourceChanged__e platEvent=new AccountSourceChanged__e ();
for(Account acc:Trigger.New)
{
if(acc.Type!=Trigger.oldmap.get(acc.id).Type)
{
system.debug('###### Type ');
platEvent.Message__c='Account Source is changed!';
}
}
if(platEvent.Message__c!=null)
{
EventBus.publish(platEvent);
}

}
}

Use Case 2: Communicating outside Salesforce:

ABC corp ltd wants to send the Account data to external system whenever account source gets changed.

Solution:

  1. External system should subscribe to platform event ‘AccountSourceChanged’
  2. Publish platform event using flow or trigger.

Testing Platform Events in Apex code:

Platform events gets published on test event bus when published from Apex test code. Test event bus is separate from Salesforce event bus.

To test the platform events, enclose publishing of platform event in Test.StartTest() and Test.StopTest() to ensure that platform event is published. You can validate post event delivery actions after Test.StopTest().

Test.StartTest();
EventBus.Publish(<instance of platform event>);
Test.StopTest();
// Perform validations

Use Test.getEventBus().deliver() to deliver test event messages before Test.Stoptest().

Test.StartTest();
EventBus.Publish(<instance of platform event>);
Test.getEventBus().deliver();
// Perform validations
Test.StopTest();

To test platform events which are part of asynchronous process, call Test.getEventBus().deliver() in an Apex test method outside the Test.startTest() and Test.stopTest().

Test.StartTest();
//Call the asynchronous process
Test.StopTest();
// Deliver test events
Test.getEventBus().deliver();
// Perform validations

To fail publishing of platform events use Test.getEventBus().fail(). It enables validation of post failure actions.

Monitor Platform Events Usage:

Platform events usage can be monitored by querying ‘PlatformEventUsageMetric’.


/*
NAME:PLATFORM_EVENTS_PUBLISHED OR PLATFORM_EVENTS_PUBLISHED
PLATFORM_EVENTS_PUBLISHED-Number of platform events published
PLATFORM_EVENTS_DELIVERED-Number of platform events delivered to CometD and Pub/Sub API clients, empApi Lightning components, and event relays
StartDate and EndDate should be in UTC format.
for example: 2020-08-03T11:00:00.000Z
*/

SELECT Name, StartDate, EndDate, Value FROM PlatformEventUsageMetric
WHERE Name='PLATFORM_EVENTS_DELIVERED'
AND StartDate=<start date> AND EndDate=<end date>

Reference:

https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_test_deliver.htm

--

--