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 PubSub class in your .h file :

#import <Cobalt/PubSub.h>

[[PubSub sharedInstance] 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 :

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

Using Cobalt Subscribe

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

@interface MyClass : MyParentClass <PubSubDelegate>

[[PubSub sharedInstance] unsubscribeDelegate:delegate fromChannel: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:() {
    [[PubSub sharedInstance] 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.

[[PubSub sharedInstance] 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 :

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