Is using event library like Otto or EventBus a recommended way to handle relations between Activities, Fragments, and background threads

Cheok Yan Cheng picture Cheok Yan Cheng · Mar 5, 2015 · Viewed 15.8k times · Source

In most of the case, when dealing with case

  • User thread (AsyncTask) to perform background processing
  • Pass back calculated result back to Activity or Fragment
  • Activity or Fragment re-creation might happen before user thread finishes its background processing

So far, from many reliable sources, I can see the recommended way is using Retained Fragment

Sources

From time to time, I heard event bus libraries is good for handling relations between Activities, Fragments, and background threads. (Please refer to https://github.com/greenrobot/EventBus. It states that performs well with Activities, Fragments, and background threads)

I came across some really popular event bus libraries

I was wondering, when comes to handle relations between Activities, Fragments, and background threads, how is event bus approach different from Retained Fragment approach?

Which ways is a recommended way?

Answer

EpicPandaForce picture EpicPandaForce · Mar 5, 2015

The event bus and Otto are not "recommended ways" by the Android developer guide primarily because they are third party libraries to simplify the task. And I believe Otto is fairly new, so older guides obviously aren't using it.

I personally like Otto, it's what I use and I haven't had any problems with it so far. But of course, that's because it suited my use-cases.

I have an example on how I used Otto here.

EDIT from the future: if you need an event bus, greenrobot/EventBus is better than Otto. Also, in some cases, LiveData<T> is perfectly sufficient instead of using event bus (which instead of emitting events to anyone, only emits to subscribers).