Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Bus equivalent in iOS

Heard about java 'publish-subscribe' style communication between components without requiring the components to explicitly be aware of each other, which is Event bus.It seems that using event bus we can communicate between different classes very easily with less coding needed.I know that NSNotifications in iOS also do this. NSNotification is not a replacement here.Please let me know apart form delegation pattern what is a good solution in iOS which is a good replacement for EventBus for communication between classes.?

like image 980
jishnu bala Avatar asked Jun 18 '15 04:06

jishnu bala


2 Answers

With Swift you can use SwiftEventBus. It's just a nice wrapper around NSNotificationCenter and DispatchQueue.

Register to an event:

SwiftEventBus.onMainThread(target, name: "someEventName") { result in
    // UI thread
    // Do something when the event occurr
}

Trigger an event:

SwiftEventBus.post("someEventName")

And if you need to customize it, the source code is short, clear and easy to understand.

like image 136
lifeisfoo Avatar answered Nov 12 '22 06:11

lifeisfoo


I think you can use NSNotificationCenter for this, I read your comment about it is one-to-many and it's true by default but you can specify from which object do you want to receive messages like this:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(someSelector:)
                                             name:@"MyPersonalNotification"
                                           object:someOtherObject];

Here you will receive the MyPersonalNotification in someSelector: only when someOtherObject post it. This made the communication one-to-one.

Also you can use the Key-Value Observing API but I personally found it somewhat uncomfortable.

like image 21
Bruno Berisso Avatar answered Nov 12 '22 05:11

Bruno Berisso