Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event bus and lifecycle of android ui components

I have been searching for perfect android application architecture and read a few great blogposts on this topic.

1) http://www.mdswanson.com/blog/2014/04/07/durable-android-rest-clients.html

2) http://birbit.com/a-recipe-for-writing-responsive-rest-clients-on-android/

Both posts describe how to utilize event bus for communication among android components (activity, fragments, service).

One, but very important topic was not covered. How to handle events which were posted to UI components when they were paused.

For example: service is posting event on completion of downloading data to activity. And at this moment activity is paused. As event bus is being unregistered in onPause(), we are loosing this event completely.

EvenBus from greendao offers stickyevents. But they can cause memory leaks if not removed.

Otto from square introduces "Producer" pattern, which can be used instead of sticky events.

First solution can cause memory leaks if sticky event is not removed manually.

The second requires to keep data somewhere until Producer method returns it to Subscribers. This solution seems to be more correct, but requires to write more code.

Could anyone please share with ideas how to tackle this edge case? Any clean solutions?

like image 545
Araz Abishov Avatar asked Dec 19 '14 10:12

Araz Abishov


1 Answers

I have also used a very elegant architecture using the EventBus. It's an excellent tool for separating your UI from the business and comms layer and preventing long running network or db jobs from trying to update a UI that has already been destroyed. I could talk about it all day, but I will focus on your problem.

Using sticky events is, in most cases, and IMHO, totally fine. Yes technically it is a memory leak because the event is stored in memory and nothing except the eventbus is referencing it... yet. But sticky events by definition are all technically memory leaks, until you actually use them right? So if you start up your fragment and use the sticky event then suddenly, its not a memory leak anymore.

Anyway, without getting too religious, sticky events are totally fine so long as the event doesn't contain a million records or large data structures like images. Then your memory leak theory starts to make more sense.

However, what you are really trying to do is cache the results of the network call right? So...

I would suggest implementing some intelligent and persistent http caching. Robospice does a lot of this out of the box for you. You can define cache keys, cache file locations and cache timeouts - really cool things. This removes the cache from the memory (ie the sticky event) and into a file, further down in the comms layer which is probably much cleaner.

like image 104
shredder Avatar answered Sep 20 '22 15:09

shredder