androidkotlinchatpubnub

android kotlin pubnub sdk sometimes does not work


I am using pubnub android kotlin sdk for chat function. However i have 3 different fragments on which i use pubnub's functions. H

ence i have created a service which listens to incomings events from pubnub and post it on fragments as a part of ui.

There are multiple channels on 3 different fragments. One fragment is for one to one messaging and another fragment is for group messaging. I subscribe channels on the each fragment whenever i open the fragment but do not unsubscribe when i leave the fragment. Currently my pubnub works well whenever i open the first fragment for one to one messaging but when i open another fragment for group messaging the listener on the first fragment stops listening to incoming messages or events.

My question here is, shall i subscribe all the channels once in the first time or subscribe each on their corresponding fragment page. Also i would like to know what is the best practice to use pubnub in android kotlin. Sharing the code is little bit difficult for me.


Solution

  • PubNub client object and SubscribeCallback listener scope

    If you want to stay subscribed to the channels with each Fragment you enter and leave, you need to create your PubNub client object and * SubscribeCallback listener* at the app scope (MainActivity, perhaps, as a singleton) or some scope that is above the Fragments' scope, like the View that contains those Fragments, assuming the Fragments are in the same View, if not then move to the next highest scope (Activity).

    So as you subscribe to new channels when you enter a Fragment, those channels are just added to the single subscribe request of the higher-scoped PubNub client object, and messages published to those channels will be received in the listener in that higher scope.

    If you wanted to leave those channels as you leave the Fragment they belong to, of course, you can just unsubscribe from those channels.

    In a nutshell, your PN client and listener need to NOT go out of scope and get GC'ed.