Skip to content

Publish Subscribe on iOS

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

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

Using Cobalt Publish

first, import the Cobalt class in your .h file :

#import <Cobalt/Cobalt.h>

[Cobalt publishMessage:message toChannel:channel];

  • message : (NSDictionary) 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 :

[Cobalt publishMessage:@{@"myValue": @42}
             toChannel:@"myChannel"];

Using Cobalt Subscribe

Subscribe needs a delegate to catch the message. Add the delegate to your class :

@interface MyClass : MyParentClass <PubSubDelegate>

[Cobalt subscribeDelegate:delegate toChannel:channel];

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

Example with the current class as PubSubDelegate :

@implementation MyClass {
...
// later somewhere : 
- (void)myFunction:() {
    [Cobalt subscribeDelegate:self
                    toChannel:@"myChannel"];
}
...
// later again : 
- (void)didReceiveMessage:(nullable NSDictionary *)message
                onChannel:(nonnull NSString *)channel {
    if ([channel isEqualToString:@"myChannel"]) {
        // Do something with the message
    }
}   

Using Cobalt Unsubscribe

Unsubscribe a PubSubDelegate to messages from the specified channel.

[Cobalt unsubscribeDelegate:delegate fromChannel:channel];

  • channel : (string) The name of the channel you want to unsubscribe.
  • delegate : (PubSubDelegate) The Cobalt PubSubDelegate you used to handle the messages.

Example :

[Cobalt unsubscribeDelegate:self
                fromChannel:@"myChannel"];
Clone this wiki locally