Search code examples
javaandroidkotlinmvvmviewmodel

Where to Save ViewModel State in Android's MVVM?


As a beginner to Android development, I am trying to clean up my codebase from my first app by converting it to the recommended MVVM structure. What I am currently stuck on, is trying to figure out the best way to store my view model's state.

In this example, the state I need to store is simply an ArrayList of strings (indicating which checkboxes in a recyclerview are checked). I am currently storing this ArrayList inside of my ViewModel as a field, wrapped inside of a MutableLivedata object, which my activity observes. This method of storing the ViewModel state as a field does not seem viable in the long run. I can imagine as my app grows my ViewModel classes would get quite bloated and messy.

I currently use a Firebase Realtime Database to store my data that I need persisted, accessed through a repository just as Android Architecture recommends. My ViewModel's state, however, does not need to be persisted after the app closes, so it would definitely not make sense to make network calls to my Firebase Database for it.

My question is: Where would make the most sense to save my ViewModel's state? The semi-sensible options I see in front of me are saving it as fields in my ViewModel class (my current approach), saving it in a Room database (and resetting the database each time the app is killed), or saving it as fields in my repository class (doesn't seem right). I'm open to suggestions!


Solution

  • It depends on your needs:

    • If you want to keep state just for configuration changes, you do not need to do anything more. ViewModel will handle it for you.
    • If you want to see the same state when you come back to that screen after closing it, then I would recommend to use a local cache solution such as Room. You can create a repository on top of room and inject it into your Viewmodel.
    • If you want to keep state until application closes, you can also create an in-memory repository (a singleton repo with the state). When application is killed that memory will be reclaimed by the OS so that they will be cleared.

    In any case storing data remotely does not seem to be the the solution that you are looking for.

    I would also not rely on memory cache solution because of Android system memory reclaim situations.

    You can go with the cache solution and clear your cache when you open the app again.