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
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
Fragments in order to inject a scoped "service".
XyzManager(where Xyz = the actual functionality this manager is responsible for)
@Providesmethod (in Dagger's module) with
getComponent()method to your custom
XyzManager while using the same component -
If you take the above steps, then all your
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.