3

I see several blog post around Lightning and Streaming API integration but it seems not working due to authorization failure and don't complain any error for API version greater than 36, I tried to hard code valid access toke and sessionid for testing still no luck. Did anyone try streaming api and lightning components recently?

enter image description here

enter image description here

  • Are you targeting your own streaming topic or a built in one? You mention API version 36.0, is it working if you use that version or earlier? – Daniel Ballinger Jul 19 '17 at 0:41
  • 1
    Sorry, no issue with sessionId, i take it back, the reason i got confused was its not showing in debug console. The real problem is in $A.getCallback which I'm missing in cometd.subscribe function. Thanks a lot Eric! – realnumber Jul 19 '17 at 1:48
7

As a data point I would be interested to hear if you get this working for you what the key modification was to do so. Maybe "OAuth" instead of "Bearer", the callback pattern, the versions, etc.

So here is what I am doing (Full lightning component and in Lightning out), YMMV:

Keep in mind, it seems that the first step to troubleshooting the streaming API when it does not appear to be capturing an event you think it should is to delete the push topic and reinsert it. At least that has been my experience

Component - v40.0

<aura:component description="[Your Description]" controller="[Your Controller]">

    <aura:handler event="c:StreamingAPIEvent" action="{!c.handleShowNotificationEvent}"/>

    <ltng:require scripts="{!join(',',
            $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.init}"
    />

   .......

</aura:component>

Controller - v40.0

({
    init: function (component, event, helper) {
         helper.startListening(component, event, helper);
    },
    handleShowNotificationEvent: function (component, event, helper) {
        helper.handleShowNotificationEvent(component, event, helper);
    }
})

Helper - v40.0

({
    startListening: function (component, event, helper) {
        //Get a valid Session Id
        var sessionAction = component.get("c.getUserSession");

        sessionAction.setCallback(this, function (a) {
            var sid = a.getReturnValue();

            $.cometd.init({
                url: '/cometd/39.0',
                requestHeaders: {Authorization: 'OAuth ' + sid},
                appendMessageTypeToURL: false,
                logLevel: [ "warn" | "info" | "debug]
            });

            //subscribe
            $.cometd.subscribe('/topic/[Your Topic Name]', $A.getCallback(function (message) {
                // console.log('in subscribe');
                var sEvent = $A.get("e.c:StreamingAPIEvent");

                sEvent.setParams({
                    topic: 'The Topic',
                    data: message.data.sobject,
                    event: message.data.event
                }).fire();

            }));

            //closes connection of window close
            window.onbeforeunload = function () {
                $.cometd.disconnect();
            };
        });

        $A.enqueueAction(sessionAction);

    },
    handleShowNotificationEvent: function (component, event, helper) {

        var data = event.getParam('data') || '';

        if($A.util.isEmpty(data)){
            return;
        }

        ........

    }
})

Application Event - v40.0

<aura:event type="APPLICATION" access="global" description="Event template">
    <aura:attribute name="topic" required="true" type="String"
                    description="PushTopic name"/>
    <aura:attribute name="data"  type="Map"
                    description="Sobject"/>
    <aura:attribute name="event"  type="Map"
                    description="Event"/>
</aura:event>

Apex Controller Method - v39.0

@AuraEnabled
public static string getUserSession() {
    return userInfo.getSessionId();
}

Note that the cometd URL in the code is at 39 but the lightning component bundle is at 40. I have not tested with the /cometd/40.0 URL. If you get the 39 working and can test with the 40 and report back that would be great as I cannot create a new version of the package to test the 40 URL yet. But this does work on the v40 of the component bundle in a production org within a managed package

Also, the apex controller class is at v39.0. Have not tested with v40

The user session works fine for me so i hope it does not break later or I will have to redesign the entire application.

Note This only works when subscribing to a push topic within the same org. I have not been able to connect in any way to another SF org to subscribe to a push topic there. Wish I could figure that out :)

  • Eric, thanks for your great explanation and example code. I'm adapting this for an app that has many components that will use the event, so I'm creating an invisible (no markup) component called StreamingAPIListener, which subscribes to the event and fires the Application Event -- and that's all. I can imagine reusing this component in lots of apps. It's just a bridge between PushTopic and ApplicationEvent. – PatMcClellan__c Feb 9 '18 at 0:15
  • This is great! Out of interest, how long can you leave the Lightning component page open in a browser before the CometD connection times out? – Aislinn Hayes Jul 24 '18 at 14:56
  • 1
    @AislinnHayes no idea never tested it. It should not time out though it should maintain the connection. – Eric Jul 24 '18 at 16:36
  • Cool, I'm actually doing some testing on this now. 5 minutes and 10 minutes, fine. I have a funny feeling that my computer is breaking the connection whenever it goes to sleep which is why I was seeing intermittent issues. Thanks :) – Aislinn Hayes Jul 25 '18 at 15:05
  • 1
    @Eric, something interesting I found with having this component open in multiple tabs in the Lightning console. I'm playing around with it now, and the component in each tab is overwriting the previous cometd subscription (this is preventing me from putting a filter on the pushtopic/conditionally firing the event). I removed the filter on the query, and put a $cometd.isDisconnected() check before initialising the cometd connection. Would have preferred to keep the filtering on the pushtopic to prevent over-firing of the application event but looks like it's unavoidable. What do you think? – Aislinn Hayes Aug 9 '18 at 8:21

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.