Skip to content

Publish Subscribe on Android

Guillaume Gendre edited this page Jun 7, 2019 · 4 revisions

This page is part of the Cobalt Publish/Subscribe pages. Don't miss the others.

Using Cobalt Publish

first, import the Cobalt class :

import org.cobaltians.cobalt.Cobalt;

Cobalt.publishMessage(message, channel);

  • message : (JSONObject) The message that will be sent in the channel.
  • channel : (string) The name of the channel in which you want to send your message.

Example :

JSONObject message = new JSONObject();
try {
    message.put("myValue", 42);
} catch (JSONException e) {
    e.printStackTrace();
}
Cobalt.publishMessage(message, "myChannel");

Using Cobalt Subscribe

You can either create an interface on the fly, either add the interface to your current class and add specified method to catch the message.

To use the PubSubInterface, import it :

import org.cobaltians.cobalt.pubsub.PubSubInterface;

Cobalt.subscribeToChannel(channel, pubSubInterface);

  • channel : (string) The name of the channel you want to subscribe.
  • pubSubInterface : (PubSubInterface) A Cobalt PubSubInterface to handle the messages when they'll come. This PubSubInterface has one method onMessageReceived receiving message and channel.

Example with an inline PubSubInterface :

This method is cool if you only subscribe to a few messages.

Cobalt.subscribeToChannel("myChannel", new PubSubInterface() {
    @Override
    public void onMessageReceived(@Nullable JSONObject message, @NonNull String channel) {
        // Do something with the message
        // In this case, you don't care about the channel
        // because your interface is built only for this channel
    }
});

Example with the current class as PubSubInterface :

This method is better if you subscribe to a lot of messages in your class.

public final class myClass implements PubSubInterface {
...
// later somewhere : 
public void myFunction() {
    Cobalt.subscribeToChannel("myChannel", this);
}

// later again : 
@Override
public void onMessageReceived(@Nullable JSONObject message, @NonNull String channel)
{
    switch(channel) {
        case "myChannel":
            if (message != null) {
                // Do something with the message
            }
            break;
    }
}   

Using Cobalt Unsubscribe

Unsubscribe a PubSubInterface to messages from the specified channel.

Cobalt.unsubscribeFromChannel(channel, pubSubInterface)

  • channel : (string) The name of the channel you want to unsubscribe.
  • pubSubInterface : (PubSubInterface) The Cobalt PubSubInterface you created to handle the messages.

Example :

Cobalt.unsubscribeFromChannel("myChannel", this)
Clone this wiki locally