Tuesday, 11 September 2012

Guava's EventBus and Android's async tasks

Android requires that you do all network processing on non-UI threads. This is good business as it means unexpected exceptions aren't going to crash your app. It can be a little problematic when you need to be notified of the different outcomes of your various network activity. You need to notify an activity, it needs to notify one of it's components.

The Callback Approach

This is essentially like handing a reference to the caller of the process. The process then calls an appropriate method on the caller, depending on the outcome.

The Guava EventBus Approach

This approach decouples the caller from the process. The caller can register for different events on the event bus after which, any process can put that event on the event bus. The registered processes with get notified.

You have to define those events but they can be empty or you can wrap anything you need in them.
Then all you have to do is subscribe for the event from the activity. It doesn't matter what you call the method... what matters is the parameter must match an event that will be put on the message bus.

Why is the event bus better? 

Well it decouples the method responding to the outcome of the network activity or whatever from the task doing this. You don't have to pass a reference of the thing doing the responding to the task. Another benefit here is that anything can register to respond to this event. Be it the activity, or one of it's fragments, it's action bar, or whatever. Nice!

No comments:

Post a Comment