For the More Curious: Local Events

Broadcast intents allow you to propagate information across the system in a global fashion. What if you want to broadcast the occurrence of an event within your app’s process only? Using an event bus is a great alternative.

An event bus operates on the idea of having a shared bus, or stream of data, that components within your application can subscribe to. When an event is posted to the bus, subscribed components will be activated and have their callback code executed.

EventBus by greenrobot is a third-party event bus library we have used in some of our Android applications. You could also use Square’s Otto, which is another event bus implementation, or RxJava Subjects and Observable.

Android does provide a way to send local broadcast intents, called LocalBroadcastManager. But we find that the third-party libraries mentioned here provide a more flexible and easier-to-use API for broadcasting local events.

Using EventBus

To use EventBus in your application, you must add a library dependency to your project. Once the dependency is set up, you define a class representing an event (you can add fields to the event if you need to pass data along):

    class NewFriendAddedEvent(val friendName: String)

You can post to the bus from just about anywhere in your app:

    val eventBus: EventBus = EventBus.getDefault()
    eventBus.post(NewFriendAddedEvent("Susie Q"))

Other parts of your app can subscribe to receive events by first registering to listen on the bus. Often you will register and unregister activities or fragments in corresponding lifecycle functions, such as onStart(…) and onStop(…):

    // In some fragment or activity...
    private lateinit var eventBus: EventBus

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        eventBus = EventBus.getDefault()
    }

    public override fun onStart() {
        super.onStart()
        eventBus.register(this)
    }

    public override fun onStop() {
        super.onStop()
        eventBus.unregister(this)
    }

You specify how a subscriber should handle an event by implementing a function with the appropriate event type as input and adding the @Subscribe annotation to that function. Using the @Subscribe annotation with no parameters means the event will be processed on the same thread it was sent from. You could instead use @Subscribe(threadMode = ThreadMode.MAIN) to ensure that the event is processed on the main thread if it happens to be issued from a background thread.

    // In some registered component, like a fragment or activity...
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNewFriendAdded(event: NewFriendAddedEvent) {
        // Update the UI or do something in response to an event...
    }

Using RxJava

RxJava can also be used to implement an event broadcasting mechanism. RxJava is a library for writing reactive-style Java code. That reactive idea is broad and beyond the scope of what we can cover here. The short story is that it allows you to publish and subscribe to sequences of events and gives you a broad set of generic tools for manipulating these event sequences.

So you could create something called a Subject, which is an object you can publish events to as well as subscribe to events on:

    val eventBus: Subject<Any, Any> =
             PublishSubject.create<Any>().toSerialized()

You can publish events to it:

    val someNewFriend = "Susie Q"
    val event = NewFriendAddedEvent(someNewFriend)
    eventBus.onNext(event)

And subscribe to events on it:

    eventBus.subscribe { event: Any ->
        if (event is NewFriendAddedEvent) {
            val friendName = event.friendName
            // Update the UI
        }
    }

The advantage of RxJava’s solution is that your eventBus is now also an Observable, RxJava’s representation of a stream of events. That means that you get to use all of RxJava’s various event manipulation tools. If that piques your interest, check out the wiki on RxJava’s project page: github.com/​ReactiveX/​RxJava/​wiki.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
44.192.53.34