4
Persisting UI State

Destroying and re-creating activities on rotation can cause headaches, such as GeoQuiz’s bug of reverting to the first question when the device is rotated. To fix this bug, the post-rotation MainActivity instance needs to retain the old value of currentIndex. You need a way to save this data across a runtime configuration change, like rotation.

Luckily, there is a class that survives rotation that you can use to store your state. In this chapter, you will fix GeoQuiz’s UI state loss on rotation bug by storing its UI data in a ViewModel.

A ViewModel is the perfect complement to an Activity because of its simple lifecycle and ability to persist data across configuration changes. It is usually scoped to a single screen and is a useful place to put logic involved in formatting the data to display on that screen. Using a ViewModel aggregates all the data the screen needs in one place, formats the data, and makes it easy to access the end result.

You will also address a bug that is harder to discover, but equally problematic – UI state loss on process death – using a SavedStateHandle. This class allows you to temporarily store simple data outside the lifecycle of your app’s process.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.251.169