Home » Swift » Event Bus equivalent in iOS

Event Bus equivalent in iOS

Posted by: admin January 3, 2018 Leave a comment

Questions:

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.?

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.

Questions:
Answers:

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.

Questions:
Answers:

Have a look at tolo.
The functionality is somewhat similar to an event bus and it has one big advantage over NSNotification as you don’t have to unregister when deallocating (like in iOS9).