maschin maschin - 1 month ago 13
reST (reStructuredText) Question

Android - keep webservice results in memory

In my Android app I have to query some user/session dependent data from a rest webservice. Now I need a way to keep the received webservice results in memory, so that serveral activities/fragments can access them.
I don't want to persist the data (for example a list of the users bank accounts) into a database on the device, because the data expires after a while or when the user logs out.
I also don't want to request the data again and again from webservice, when the user navigates to another activity.

Are there any approved patterns to keep a set of data (some pojo's with more or less properties) in memory during the application is running?

Just for info: I'm experimenting with dagger2, mvp, retrofit2, rxandroid

Regards
Martin

Answer

If you already experimenting with Dagger 2, then all you need to do is instantiate a component in Application and use this component in your Activities and Fragments in order to inject a scoped "service".

For example:

  • Create a class named XyzManager (where Xyz = the actual functionality this manager is responsible for)
  • Annotate its @Provides method (in Dagger's module) with @Singleton scope
  • Make sure that the component that injects XyzManager instantiated in Application and add getComponent() method to your custom Appliaction class
  • In your Activities and Fragments inject XyzManager while using the same component - ((MyApplication)getApplication()).getComponent().inject(this)

    If you take the above steps, then all your Activities and Fragments will get a reference to exactly the same instance of XyzManager, and the data you cache in this manager will be accessible everywhere.

    The structure you would get is very similar to the structure described in this answer.

Please note that this approach is much better than resolving to static things (e.g. Singleton pattern, or what @KhalidTaha suggested in his answer).

You might want to take a look at my post concerning Dagger 2 scopes if you need a detailed information on that aspect of the framework.