Event-Driven Development in Salesforce

In this session we will talk about Event-Driven Development in Salesforce. Let’s take a look into the many ways events have changed the way we develop on Salesforce – we’re going to be taking a look at Lightning Message Service, CustomEvent, the EMP API, Platform Events, Change Data Capture, WebSocket, and Consent Events!

Event Driven Development

  • Decouples point to point integrations
  • Real-time notifications through Publishing & Subscribing
  • Send messages and data to a single destination

Events & Salesforce

How does it translate? 

Browser Events

Communication across the page

JavaScript Events : Communicate across the the dom using DOM events or Custom events. They adhere to a generic specification that can be used across all types of browser pages and applications.   

Lightning Message Service : Specific to Salesforce – they allow you to communicate in a similar way to JS events however route through a secure message channel

Custom Events

Allow you to Define, Dispatch and Subscribe to an event within the browser. These are not controlled by locker service in any way.

Publishing Event

const event = new CustomEvent('message',{
    detail: {
        value: this.value
    },
    bubbles:true
});

this.dispatchEvent(event);

Subscribing Event

connectedCallback(){
    window.addEventListener('message', this.handleMessage, false);
}

handleMessage = (event) => {
    let detail = event.detail.value;
}

disconnectedCallback(){
    window.removeEventListener('message', this.handleMessage, false);
}

Lightning Message Service

Same concept, different approach

import CHANNEL_NAME from '@salefsorce/messageChannel/Channel_Name__c';

doSomething(){
    const payload = {};
    publish(this.messageContact,CHANNEL_NAME,payload);
}

MessageContext : Opens up LMS to the component through createMessageContext();

Publish : Allows you to publish a message through the message channel

Subscribe : Allows you to subscribe to a message channel and pass the result to a method

Platform Events

Platform Event is based on Event-Driven Architecture which enable apps to communicate inside and outside of Salesforce. Platform events are based on the publish/subscribe model and work directly with a message bus which handles the queue of incoming events and processes listening for them. This is built in real time integration patterns in the Salesforce Platform which helps to reduce point-to-point integration

Here is some terminology we should remember :-

  • Event : A change in state that is meaningful in a business process.
  • Event message / Notification : A message that contains data about the event.
  • Event producer : The publisher of an event message over a channel.
  • Channel : A conduit in which an event producer transmits a message. Event consumers subscribe to the channel to receive messages. Also referred to as event bus in Salesforce.
  • Event consumer : A subscriber to a channel that receives messages from the channel.

Publish Messages

  • Apex
  • Flows
  • APIs

Subscribe to Message

  • Apex Triggers
  • Flow
  • External Applications

Publishing

As easy as creating a record

public static void PublishServiceAlert() {
    ServiceAlert__e alert = new ServiceAlert__c();
    alert.VehicleId__c = '500S000000EjcSOIAZ';
    alert.Message__c = 'This is a message';
    Database.SaveResult sr = EventBus.publish(alert);
}

Or using the Rest API

/services/data/v51.0/sobjects/Event_Name__e/

Subscribing

Subscribe via Trigger

trigger ServiceAlertTrigger on ServiceAlert__e (after insert) {
    for (ServiceAlert__e event : Trigger.New) {
        // Do something
    }
}

Via Flow

EMP API

Quickly subscribe to events in Lightning Components to listen in real time

handleSubscribe() {
    const messageCallback = function(response) {
    // Do Something
    };

    subscribe(this.channelName, -1, messageCallback.bind(this)).then(response => {
        console.log('Subscription request sent to: ', JSON.stringify(response.channel));
        this.subscription = response;
    });
}

Honorable Mentions

Change Data Capture : Sends platform events containing all of the fields changed on a record.

Consent Events : Sends platform events each time a privacy related field or object is changed.

Real-time Event Monitoring : Sends platform events each time an event monitoring related action is taken.

Websockets

Listen to external events as they’re streamed

Recording

Please check below recording for more details.

Agenda

  • Event Driven Development
  • Browser Events
  • Pub Sub
  • Web Sockets 
  • Honorable Mentions
YouTube video

Amit Chaudhary
Amit Chaudhary

Amit Chaudhary is Salesforce Application & System Architect and working on Salesforce Platform since 2010. He is Salesforce MVP since 2017 and have 17 Salesforce Certificates.

He is a active blogger and founder of Apex Hours.

Articles: 463

One comment

  1. Hello, I have a simple need and I am surprised to find no example about it. On an external event I want to be able to dynamically modify a lightning component either of a given user or of all users (component in a utility bar or in an object). What solution do you suggest to use ?

Leave a Reply

Your email address will not be published. Required fields are marked *