Salesforce Platform events subscribe from aura component

 1] Create a push topic where push notifications would be created once new records are inserted in select SObject.

PushTopic pushTopic = new PushTopic();

pushTopic.Name = 'PopUpAPIUpdates';

pushTopic.Query = 'Select Id,other fields from '+ 'SObject';

pushTopic.ApiVersion = 48.0;

pushTopic.NotifyForOperationCreate = true;

pushTopic.NotifyForOperationUpdate = false;

pushTopic.NotifyForOperationUndelete = false;

pushTopic.NotifyForOperationDelete = false;

pushTopic.NotifyForFields = 'Select';

insert pushTopic;


2] Place following line in Parent Aura component which wants to handle platform events.

<c:EmpApiSubscribe channelName="/topic/PopUpAPIUpdates" onEmpEvent="{!c.handleMessage}" />

 

3] Place following content in EmpApiSubscribe component

<aura:component access="global">

    <!-- ChannelName, which needs to subscribed -->

    <aura:attribute name="channelName" type="String" required="true"/>

    <!-- Save the reference of current subscription, which can be unsubscribe later on -->

    <aura:attribute name="subscription" type="Object"/>

    <!-- This event is fired when a component is destroyed. 

Handle this event if you need to do custom cleanup when a component is destroyed.-->

    <aura:handler name="destroy" value="{!this}" action="{!c.unsubscribe}"/>

<!-- init event -->

    <aura:handler name="init" value="{!this}" action="{!c.subscribe}"/>

    

    <!-- empApi component which will be used to subscribe/unsubscribe to a channel -->

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

    

    <!-- Component event, which will be fired once the message is received

         This event will be handled by parent component to perform needful action on stream event -->

    <aura:registerEvent name="onEmpEvent" type="c:EmpEvent"/>

</aura:component>


4] EmpApiSubscribe front end controller.

({

    subscribe: function(component, event, helper) {

        

        // Get the empApi component.

        var empApi = component.find("empApi");

        // Get the channel name from attribute

        var channel = component.get("v.channelName");

        //fetch latest events

        var replayId = -1;

        

        // Callback function to be passed in the subscribe call.

        // After an event is received, this callback fire a custom

        // event to notify parent component and pass payload object

        var subscribeCallback = function (message) {

            console.log('message.data'+message.data);

            //Fire the component event to notify parent component

            var messageEvent = component.getEvent("onEmpEvent");

            if(messageEvent!=null) {

                messageEvent.setParam("empData", message.data);

                messageEvent.fire();                            

            }

            //Display event data in browser console

            console.log("Received [" + message.channel +

                        " : " + message.data.event.replayId + "] payload=" +

                        JSON.stringify(message.data.payload));

        }.bind(this);

        // Register error listener and pass in the error handler function.

        empApi.onError(function(error){

            console.log("Received error1 ",  JSON.stringify(error));

        }.bind(this));

        

        // Subscribe to the channel and save the returned subscription object.

        empApi.subscribe(channel, replayId, subscribeCallback).then(function(value) {

            console.log("Subscribed to channel " + channel);

            component.set("v.subscription", value);

        });

    },

    

    /**

     * This function will be fired once the component is destroyed

     * It will call unsubscribe method of empApi component

     * @version 1.0.0

     * */

    unsubscribe : function (component, event, helper) {

        // Get the empApi component.

        var empApi = component.find("empApi");

        // Get the channel name from attribute

        var channel = component.get("v.channelName");

        

        // Callback function to be passed in the unsubscribe call.

        var unsubscribeCallback = function (message) {

            console.log("Unsubscribed from channel " + channel);

        }.bind(this);

        

        // Error handler function that prints the error to the console.

        var errorHandler = function (message) {

            console.log("Received error2 ", message);

        }.bind(this);

        

        // Object that contains subscription attributes used to

        // unsubscribe.

        var subscription = {"id": component.get("v.subscription")["id"],

                            "channel": component.get("v.subscription")["channel"]};

        

        // Register error listener and pass in the error handler function.

        empApi.onError(function (error) {

            console.log("Received error ", error);

        }.bind(this));

        

        // Unsubscribe from the channel using the sub object.

        empApi.unsubscribe(subscription, unsubscribeCallback);

    },

})


5] In front end controller of parent aura component

handleMessage : function(component, event, helper) {

        const param = event.getParam('empData'); //made changes here 'message'

         //Invoke business logic api method and pass to it attributes of param.sobject

        });

        $A.enqueueAction(action);

    }


Help guide: https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_subscribe_lc.htm#:~:text=Examples-,Subscribe%20to%20Platform%20Event%20Notifications%20in%20a%20Lightning%20Component,and%20listening%20to%20event%20messages.

 

Setup VSCode with Salesforce

Step by Step guide to setup VSCode with Salesforce Install vscode Install Salesforce CLI (developer.salesforce.com/tools/sfdxcli) Perform fo...