ViewModel does not retain values after fragment rotation

Cazimir Roman
Oct 23, 2020

Have you tried implementing the MVVM architecture pattern in Android with Kotlin only to test the screen rotation and come to the conclusion that the values, which were supposed to stay saved in the ViewModel, are resetting?

Take a look at the above ViewModel which is used in a fragment called MainFragment:

Example of ViewModel with selectedPosition = 0

The selectedPosition variable is 0 by default and should hold the currently selected position of a UI widget.

The ViewModel is at some point in time updated to change the value of selectedPosition to 2.

Let’s say you are inflating the fragment using the FragmentManager in MainActivity.kt in onCreate():

The above code works and each time onCreate() is called a new instance of the fragment is instantiated. The only problem is that if we are expecting the new value for selectedPosition to appear in our fragment, we will not see it because according to our code above a fresh instance of the fragment will be instantiated and the corresponding ViewModel will also have the default value for selectedPosition = 0.

Solution

When the activity is recreating try to check if there is a Bundle saved in on savedInstanceState and if not, inflate the desired fragment. This way only one instance of the fragment will be inflated.

Happy coding!

Before you go…If you found this article helpful, click the ❤️ or 👏 button below or share the article on Facebook so your friends can benefit from it too.

--

--

Cazimir Roman

A curious developer with a passion for learning and creating innovative solutions to complex problems.