Add channels to groups and control multiple PubNub Data Streams with Stream Controller

Stream Controller Getting Started Guide

Add stream controller to any app in 5 easy steps with PubNub Data Streams

Stream Controller Getting Started Guide

1

Install PubNub

To start publishing and subscribing, we first need to access our PubNub libraries. Include the code hosted on our CDN just before closing your HTML </body> tag.

Now you can instantiate a PubNub object using your own publish and subscribe keys or use our demo keys.

/* View the Full Documentation. */
/* Instantiate PubNub */
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setPublishKey("Your Publish Key Here");
pnConfiguration.setSubscribeKey("Your Subscribe Key Here");

PubNub pubnub = new PubNub(pnConfiguration);
/* View the Full Documentation. */
/* Instantiate PubNub */
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"Your publish key"

subscribeKey:@"Your subscribe key"];
self.client = [PubNub clientWithConfiguration:configuration];
[self.client addListener:self];
<!-- View the Full Documentation. -->
<!-- Include the PubNub Library -->
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.[version number].js"></script>

<!-- Instantiate PubNub -->
<script type="text/javascript">

    var pubnubDemo = new PubNub({
        publishKey: 'Your Publish Key Here',
        subscribeKey: 'Your Subscribe Key Here'
    });

</script>
/* View the Full Documentation. */
/* Instantiate PubNub */
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.PublishKey = "Your Publish Key Here";
pnConfiguration.SubscribeKey = "Your Subscribe Key Here";

Pubnub pubnub = new Pubnub(pnConfiguration);
/***************
For all other languages,
check out the 70+ SDKs that PubNub supports
on our documentation page:
http://www.pubnub.com/docs
****************/

2

Add Channels to a Channel Group

Before we can start we need to Enable Channel Groups in your Admin Portal. Once you have done that, adding channels to a Channel Group is as simple as the single methods shown in the code snippets to the right. Specify both the channel you want to add and the Channel Group you want to add it to.
Channel groups are created when a channel is added to it, no need to worry about creating one before hand.

pubnub.addChannelsToChannelGroup()
    .channelGroup("energy")
    .channels(Arrays.asList("BIOF"))
    .async(new PNCallback<PNChannelGroupsAddChannelResult>() {
        @Override
        public void onResponse(PNChannelGroupsAddChannelResult result, PNStatus status) {

        }
    });
[self.client addChannels: @[@"BIOF"] toGroup:@"energy"
          withCompletion:^(PNAcknowledgmentStatus *status) {

    if (!status.isError) {

        // Handle successful channels list modification for group.
    }
    else {

        /**
         Handle channels list modification for group error. Check 'category' property to find out possible reason because of which request did fail.
         Review 'errorData' property (which has PNErrorData data type) of status object to get additional information about issue.

         Request can be resent using: [status retry];
         */
    }
}];
pubnubDemo.channelGroups.addChannels(
    {
        channels: ["BIOF"],
        channelGroup: "energy"
    },
    function(status) {
        if (status.error) {
            console.log("operation failed w/ status: ", status);
        } else {
            console.log("operation done!");
        }
    }
);
pubnub.AddChannelsToChannelGroup()
    .ChannelGroup("energy")
    .Channels(new string[] {
        "BIOF"
    })
    .Async(new PNChannelGroupsAddChannelResultExt((result, status) => {
    }));
/***************
For all other languages,
check out the 70+ SDKs that PubNub supports
on our documentation page:
http://www.pubnub.com/docs
****************/

3

Subscribe to a Channel Group

As simply as we have added a channel to a group, we can then subscribe to that Channel Group using the basic subscribe call.

try {
    pubnub.addListener(new SubscribeCallback() {
        @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            JsonNode msg = message.getMessage();
            System.out.println(msg);
        }
     });

     pubnub.subscribe()
        .channelGroups(Arrays.asList("energy"))
        .execute();
} catch (PubnubException e) {
    e.printStackTrace();
}
[self.client subscribeToChannelGroups:@[@"energy"] withPresence:NO];

- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {

    if (status.operation == PNSubscribeOperation) {

        // Check whether received information about successful subscription or restore.
        if (status.category == PNConnectedCategory || status.category == PNReconnectedCategory) {

            // Status object for those categories can be casted to `PNSubscribeStatus` for use below.
            PNSubscribeStatus *subscribeStatus = (PNSubscribeStatus *)status;
            if (subscribeStatus.category == PNConnectedCategory) {

                // This is expected for a subscribe, this means there is no error or issue whatsoever.
            }
            else {

                /**
                 This usually occurs if subscribe temporarily fails but reconnects. This means there was an error but there is no longer any issue.
                 */
            }
        }
        else if (status.category == PNUnexpectedDisconnectCategory) {

            /**
             This is usually an issue with the internet connection, this is an error, handle appropriately retry will be called automatically.
             */
        }
        // Looks like some kind of issues happened while client tried to subscribe or disconnected from network.
        else {

            PNErrorStatus *errorStatus = (PNErrorStatus *)status;
            if (errorStatus.category == PNAccessDeniedCategory) {

                /**
                 This means that PAM does allow this client to subscribe to this channel and channel group configuration. This is another explicit error.
                 */
            }
            else {

                /**
                 More errors can be directly specified by creating explicit cases for other error categories of `PNStatusCategory` such as: `PNDecryptionErrorCategory`, `PNMalformedFilterExpressionCategory`, `PNMalformedResponseCategory`, `PNTimeoutCategory` or `PNNetworkIssuesCategory`
                 */
            }
        }
    }
}
pubnubDemo.addListener({
    message: function(message) {
        displayNewPrice(message);
    }
})

pubnubDemo.subscribe({
    channelGroups: ["energy"]
});
try {
    pubnub.AddListener(new SubscribeCallbackExt(
        (pubnubObj, messageResult) => {
            if (messageResult != null) {
                string jsonString = messageResult.Message.ToString();
                Console.WriteLine(jsonString);
            }
        },
        (pubnubObj, presencResult) => {
        },
        (pubnubObj, statusResult) => {
            if (statusResult.Error && statusResult.Category == PNStatusCategory.PNUnknownCategory) {
                Console.WriteLine(statusResult.ErrorData.Information);
            }
        }
    ));

    pubnub.Subscribe<string>()
        .ChannelGroups(new string[] {
            "energy"
        })
        .Execute();
}
catch (Exception e) {
    Debug.WriteLine(e.ToString());
}
/***************
For all other languages,
check out the 70+ SDKs that PubNub supports
on our documentation page:
http://www.pubnub.com/docs
****************/

4

Demo

In this demo, imagine your financial portfolio app only subscribes to specific industries - Healthcare, Technology, and Finance. Even when individual stocks are selected or deselected, the app continues to subscribe to the same industry-specific channel group and updates accordingly. No additional work on the client-side is necessary!

Stock Symbols
Healthcare
Technology
Energy
Industries
Healthcare
MDRX
$100
NHC
$100
Technology
AAPL
$100
GOOG
$100
MSFT
$100
YHOO
$100
Energy
DTE
$100
BIOF
$100
No Stock Symbols Have Been Selected

5

You are now a master of Stream Controllers!

With those few steps, you've built your first PubNub application. Now the right thing to do is Tweet Your Success!

Next, Sign Up for a free PubNub account. Then add features like Security, Presence, and Storage to make your app more robust.

Get coding right away using our 70+ SDKs in your favorite language, or build on top of one of our demo applications.

logos