I'm working on a lightning component for Contact object. Every time a new Case record is created, I need to display total number of newly created cases on the Contact lightning action.

From component perspective, I can call a server action to get total cases, but I'm not sure how a server event (e.g. new case creation) will update the client side lightning component attribute.



Proper way to listen server events like create/update/delete, is to subscribe for those events using the Streaming API.

Here's, an working example how to use Streaming API in VF page. Unlike Visualforce which has $Api.sessionid, we don't have such things in LC. Since LC does not have an sessionid exposed is discussed in this question and here too, there's no straightdown approach to solve this.

As a workaround, you can get the sessionId using the from the controller using approach mentioned in this answer.(Still its an hacky way)

So I did some digging and found a example LC using Streaming API in github thanks to @ShaneMcLaughlin.

I tried to implement a bit simple version and it worked fine in my org.


<aura:component controller="StreamingCtrl">
    <ltng:require scripts="/resource/streamingapi/js/cometd.js,/resource/streamingapi/js/jquery-1.5.1.js,/resource/streamingapi/js/json2.js,/resource/streamingapi/js/jquery.cometd.js"
                  afterScriptsLoaded="{!c.doInit}" />

    <aura:attribute name="topic" type="string" required="true" />


    doInit : function(component, event, helper) {
        console.log('doing init on streamer');

        // Retrieve the session id and initialize cometd
        var sessionAction = component.get("c.sessionId");

        sessionAction.setCallback(this, function(response) {
            var state = response.getState();
            if(state  === "SUCCESS") {
                var sessionId = response.getReturnValue();
                var authstring = "OAuth " + sessionId;
                //authenticate to the Streaming API
                    url: window.location.protocol + '//' + window.location.hostname + '/cometd/36.0/',
                    requestHeaders: { Authorization: authstring },
                    appendMessageTypeToURL : false
                $.cometd.subscribe('/topic/'+component.get("v.topic"), function (message){
                    //print message when new contact is created




PushTopic pushTopic = new PushTopic();
pushTopic.Name = 'contactnew';
pushTopic.Query = 'SELECT Id, Name FROM Contact';
pushTopic.ApiVersion = 37.0;
pushTopic.NotifyForOperationCreate = true;
pushTopic.NotifyForFields = 'Referenced';
insert pushTopic;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.