Lightning Communication with Platform Events

  • You can publish platform events using Apex, REST API, Flows, and Processes. Also, you can subscribe to platform events using Apex triggers, flows, processes, a Lightning component, and a CometD-based tool.
  • But by using platform events, you benefit from an event-based programming model and a standard way of programming across your apps.
  • Platform events enable the flow of event messages within Salesforce and to or from external apps. Apps on the Salesforce platform use an Apex method to publish events and an Apex trigger or the empApi Lightning component to consume events. As an alternative to code, you can publish events with declarative tools, such as Process Builder and Flow Builder. External apps publish events using the sObject API and consume events using CometD.
  • You can use platform events in native Salesforce platform apps and external apps alike. Use platform events in the following cases:
    • To send and receive custom event data with a predefined schema
    • To publish or subscribe to events in Apex
    • For the flexibility of publishing and processing events on and off the Salesforce platform

Let’s Jump into Code

The Installation URL or the Deployment process of the complete App LWC Comms is available in our Github Repo – https://github.com/sfwiseguys/LWCComms

Create a Platform Event

In Salesforce Setup -> Platform Events, you can define a Platform Event with the set of fields. When you create a platform event, the system appends the __e suffix to create the API name of the event. 

A platform event defined with the Publish After Commit behavior is published only after a transaction commits successfully. Define an event with this option if subscribers rely on data that the publishing transaction commits. These can be rolled back

A platform event defined with the Publish Immediately behavior is published when the publish call executes. Select this option if you want the event message to be published regardless of whether the transaction succeeds. These cannot be rolled back.

Publish Platform Event Via Apex

In below example, we use an LWC to fire a Platform Event via Imperative Apex call on a button click.
And another LWC will be subscribed to this Platform event using empApi

Here, we use publishEvent() with the parameter message to fire our created Platform event-

@AuraEnabled
    public static void publishEvent(String message) {
    POV_Platform_Event__e event = new POV_Platform_Event__e(Message__c = message);

    Database.SaveResult result = EventBus.publish(event);

    if (!result.isSuccess()) {
      for (Database.Error error : result.getErrors()) {
        System.debug('Error returned: ' +error.getStatusCode() +' - ' +error.getMessage());
      }
    }
  }

Subscribe in LWC

The lightning/empApi module provides access to methods for subscribing to a streaming channel and listening to event messages. This component requires API version 44.0 or later. The lightning/empApi module uses a shared CometD connection.

In a component’s Javascript file, import methods from the lightning/empApi module using this syntax.

Note the Comments below Suitably-

import {LightningElement} from 'lwc';
import {subscribe, unsubscribe, onError} from 'lightning/empApi';

export default class Pov_emp_lwc extends LightningElement {
    channelName = '/event/POV_Platform_Event__e';
    isSubscribeDisabled = false;
    isUnsubscribeDisabled = !this.isSubscribeDisabled;
    receivedMessage;

    subscription = {};

    // Initializes the component
    connectedCallback() {
        // Register error listener       
        this.registerErrorListener();
       
    }

    // Handles subscribe button click
    handleSubscribe() {

        // ARROW function is very important here. We have to use arrow function as it does not have its own scope
        const messageCallback = (response) => {
            this.handleResponse(response);
        }

        // Invoke subscribe method of empApi. Pass reference to messageCallback
        subscribe(this.channelName, -1, messageCallback).then(response => {
            // Response contains the subscription information on subscribe call
            console.log('Subscription request sent to: ', JSON.stringify(response.channel));
            this.subscription = response;
            this.toggleSubscribeButton(true);
        });

        
    }

    handleResponse(response){
        this.receivedMessage = response.data.payload.Message__c;
    }

    
    // Handles unsubscribe button click
    handleUnsubscribe() {
        this.toggleSubscribeButton(false);

        // Invoke unsubscribe method of empApi
        unsubscribe(this.subscription, response => {
            console.log('unsubscribe() response: ' + JSON.stringify(response));
            // Response is true for successful unsubscribe
        });
    }

    toggleSubscribeButton(enableSubscribe) {
        this.isSubscribeDisabled = enableSubscribe;
        this.isUnsubscribeDisabled = !enableSubscribe;
    }

    registerErrorListener() {
        // Invoke onError empApi method
        onError(error => {
            console.log('Received error from server: ', JSON.stringify(error));
            // Error contains the server-side error
        });
    }
}

As per this demonstration of using Platform Events for communication, a Lightning Component can subscribe and listen to the Platform Events being fired from Internal or External sources-  Apex, REST API, Flows, and Processes.

Please note – This is not the ideal prescribed way of communicating between multiple lightning components on a single page as such, but For the Components to subscribe and listen to Platform Events in the org.

Thank You and Good Luck !

2 thoughts on “Lightning Communication with Platform Events

  1. Great post!!
    Could you also come up with a writing for below
    1. Salesforce to Salesforce integration using platform Events ?
    (Salesforce Org1 – Publisher | Salesforce Org2 – Subscriber)

    Like

Leave a comment