EmpJs Streaming API

Introduction 

Salesforce introduced a new component lightning:empApi  with winter 19 to support streaming API. Prior to winter 19 in order to use the streaming API, we need to upload the CometD javascript libraries to the static resource and we need to use cometD by using ltng:require along with afterscriptsloaded . But with the new EmpJs Streaming API library which subscribes to a streaming channel and listens to event messages using a shared CometD connection without using the CometD static resource. This component is supported only in desktop browsers. The lightning:empApi component provides access to methods for subscribing to a streaming channel         and listening to event messages. All streaming channels are supported, including channels for platform events, PushTopic events, generic events, and Change Data Capture events. The lightning:empApicomponent uses a shared CometD connection.

To call the component’s methods, add the lightning:empApi component inside your custom component and assign an aura:id attribute to it.

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

 

This example subscribes to a channel when you click the Subscribe button. The channel is specified in an input component. The default value provided is an example platform event channel. Replace the value with the desired channel name. A callback function on the subscribe() call prints the payload of each received event to the console. To view the event messages, enable your browser console view. The Unsubscribe button lets you stop the subscription and stop receiving event notifications.Add the following client-side controller functions. They are called by the Subscribe and Unsubscribe buttons. Each controller function calls the corresponding subscribe or unsubscribe method on the empApi component.

Step 1: Create a Pust topic

create a simple push topic as shown below the workbench.

Step 2: Use Emp Api in your code

Here is the simple component

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
    <aura:attribute name="channel" type="String" />
    <aura:attribute name="payload" type="Object" />
    <lightning:notificationsLibrary aura:id="notifLib"/>
    <lightning:empApi aura:id="empApi" />
    <lightning:input aura:id="channel" label="channel" name="channel" type="text" value="/topic/Case_Notification"/>
    <lightning:button label="Subscribe" onclick="{! c.subscribe }" />
    <lightning:button label="Unsubscribe" onclick="{! c.unsubscribe }" />
    Channel  :{!v.channel}
    
</aura:component>
({
    // Client-side function that invokes the subscribe method on the
    // empApi component.
    subscribe : function(component, event, helper) {
        // Get the empApi component.
        var empApi = component.find("empApi");
        // Get the channel from the input box.
        var channel = component.find("channel").get("v.value");
        var replayId = -1;
        // var data= [];
        
        // Callback function to be passed in the subscribe call.
        // After an event is received, this callback prints the event
        // payload to the console.
        var callback = function (message) {
            component.find('notifLib').showToast({
                "title": "Message Received!",
                "message":'Case is create with '+message.data.sobject.Status+' . Origin :'+message.data.sobject.Origin+'. Priority '+message.data.sobject.Priority,
                "variant": "pester"
            }); 
            
            
            component.set("v.payload" ,message.data.sobject);
        }.bind(this);
        
        // Error handler function that prints the error to the console.
        var errorHandler = function (message) {
            console.log("Received error ", message);
        }.bind(this);
        
        // Register error listener and pass in the error handler function.
        empApi.onError(errorHandler);
        
        var sub;
        // Subscribe to the channel and save the returned subscription object.
        empApi.subscribe(channel, replayId, callback).then(function(value) {
            console.log("Subscribed to channel " + channel);
            sub = channel;
            component.set("v.channel", sub);
        });
    },
    
    // Client-side function that invokes the unsubscribe method on the
    // empApi component.
    unsubscribe : function(component, event, helper) {
        // Get the empApi component.
        var empApi = component.find("empApi");
        // Get the channel from the input box.
        var channel = component.find("channel").get("v.value");
        
        // Callback function to be passed in the subscribe call.
        var callback = 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 error ", message);
        }.bind(this);
        
        // Object that contains subscription attributes used to
        // unsubscribe.
        var sub = {"id": component.get("v.sub")["id"],
                   "channel": component.get("v.sub")["channel"]};
        
        // Register error listener and pass in the error handler function.
        empApi.onError(errorHandler);
        
        // Unsubscribe from the channel using the sub object.
        empApi.unsubscribe(sub, callback);
    }
})

After saving the component you can enter the streaming channel name and click on subscribe.

After creating a case record you will see the notifications on the lightning page.