Declaring the currentIndex variable outside the class solves the problem

So I tried to move the currentIndex variable outside the MainActivity, as a top level variable and it worked. The value of the index is persisted across rotations, In fact it worked just like the ViewModal class and it only gets destroyed when the activity is destroyed.

Is it wrong to do so?

Moving the property to the file level will certainly work in this case, but it does have some potential side effects to watch out for. Storing data at the class level will cause the compiler to create a class to hold that property, which will be static. This is effectively creating a global state for you app that the activity can access. For GeoQuiz, this can work.

However, the issue comes up since there’s no way to ensure this data is cleaned up at the appropriate time. If you had multiple activities that needed their own index, it would not be possible with the class property since all of the instances would point to the same data.

In order to avoid this type of global state, it’s recommended to use the ViewModel since it’s guaranteed to be tied to an instance of your activity so it will be cleaned up when it’s not needed anymore.

1 Like