Android Developers
Published in

Android Developers

Illustration by Virginia Poltrack

ViewModels with Saved State, Jetpack Navigation, Data Binding and Coroutines

  1. Saved State in ViewModels — ViewModel data that survives background process restart
  2. NavGraph with a ViewModel — ViewModels and Navigation library integration
  3. Using ViewModels in data-binding — Easy data-binding with ViewModels and LiveData
  4. viewModelScope — Kotlin Coroutines and ViewModels integration

Saved State in ViewModels : ViewModel data that survives background process restart

The Challenge of onSaveInstanceState

Saved State Module

Setting up Saved State Module

implementation ‘androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha01’
  1. Construct: MyViewModel takes in SavedStateHandle as a constructor parameter.
  2. Save: The saveNewUser method shows an example of saving data in a SavedStateHandle. You save the key value pair of USER_KEY and then the current userId. As data updates in the ViewModel, it should be saved in the SavedStateHandle.
  3. Retrieve: savedStateHandle.get(USER_KEY) is an example of getting the current value saved in the SaveStateHandle.

ViewModel and Jetpack Navigation : NavGraph with a ViewModel

The Challenge of ViewModel Sharing

Navigation Graph with some screens that are in a shopping checkout flow

ViewModel NavGraph Integration

Screenshot showing how to “Move to Nested Graph”

ViewModel and Data Binding : Use your ViewModel and LiveData in Data Binding

All that LiveData boilerplate

Using Data Binding, ViewModel and LiveData

ViewModel and Kotlin Coroutines : viewModelScope

Coroutines on Android

viewModelScope

Conclusion

  1. ViewModels handle the onSaveInstanceState case with the SavedStateHandle module.
  2. You can scope a ViewModel to a Jetpack Navigation NavGraph for more precise and encapsulated data sharing between fragments.
  3. If you’re using the Data Binding library and ViewModels, you can pass your ViewModel to your binding. If you’re also using LiveData, use binding.setLifecycleOwner(lifecycleOwner).
  4. …and if you’re using Kotlin Coroutines with ViewModel, then use viewModelScope to cancel your coroutines automatically when the ViewModel is destroyed.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store