Is using event library like Otto or EventBus a recommended way to handle relations between Activities, Fragments, and background threads [closed]
Solution 1:
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).
Solution 2:
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?
I think you misunderstand two concepts:
1) preventing a task from creating again and again when you rotate your device
2) sending messages from a thread to an activity or from a service to a fragment or...
When we put a task inside a fragment we just do not want to start it again if we are rotating. Also we want getting the result back from it for example we want to update an imageView but if you pass an imageView to an asynctask and then you rotate your device if you store the imageView as a weak reference then your imageView is null after the activity has destroyed and if you store it as a strong reference then you leak the activity. so better idea is putting it inside a fragment and storing the view as a weak reference and if the activity onCreate is called updating that reference.
EventBus and Otto are very good libraries to send messages between any components or threads. you can use those or android native solution like creating interface or localBroadcastManager or handler.
how is event bus approach different from Retained Fragment approach?
I have not looked into source code of those but I think they created a singleton queue object and store your messages inside it and dequeue it to pass your messages to their listeners.