Upgrade to Pro — share decks privately, control downloads, hide ads and more …

When ViewModels Go to Die: Saving ViewModel State

When ViewModels Go to Die: Saving ViewModel State

This is a presentation given at DroidCon Americas 2020: https://www.online.droidcon.com/americas-speaker/sumayyah-ahmed

Abstract:

Contrary to our hopes, ViewModel lifecycles are not infallible. The Android OS can kill running processes, which means killing your ViewModel and all the state that you’ve saved in it, spelling impending disaster for your Activity or Fragment. Luckily, we have a new tool to maintain a seamless user experience even through process death – SavedStateHandle. This talk will use code examples to demonstrate:
• How to use SavedStateHandle to gracefully save and resurrect your ViewModel state through process death
• How to leverage Jetpack to automate state restoration with SavingStateLiveData

Sumayyah Ahmed

November 17, 2020
Tweet

More Decks by Sumayyah Ahmed

Other Decks in Technology

Transcript

  1. 6 ViewModel with status data In-process memory Android OS kills

    the process ViewModel data?? In-process memory
  2. 7 Problem: The user expects that when they come back

    to the activity, the state is the same as when they left it. For example: search bar data
  3. 8 ViewModel: Step 1 App A more serious problem: setting

    up Bluetooth-enabled hardware via an app Router: State 1 ViewModel: Step 2 App Router: State 2 Process death ViewModel: Step ?? App Router: State 2 Now your app and hardware are out of sync
  4. :(

  5. 1 2 SavedInstanceState ViewModel data Process Death SavedInstanceState Activity/Fragment ViewModel

    data SavedInstanceState Restore! SavedInstanceState New Activity/Fragment New ViewModel Activity/Fragment
  6. 1 3

  7. 1 4 The Problems with SavedInstanceState Code needs to live

    in the LifecycleOwner -> Data usage/storage logic has to be in the view class ViewModel initiation delayed till you get SavedInstanceState data
  8. 1 6 What is it? Map of key-value pairs, backed

    by Bundle VM-friendly wrapper around SavedInstanceState Allows ViewModel control over data state independent of lifecycle owner
  9. 1 7

  10. 1 9 Behind the scenes Bundle SavedInstanceState SavedStateProvider SavedStateProvider SavedStateHandle

    ViewModel SavedStateRegistryOwner (aka Activity/Fragment) SavedStateRegistryController
  11. 2 0 Limitations • Should be used to store simple

    data types: • Primitives • LiveData objects have to be parcelable • Data limit • NOT a permanent form of storage! Tied to SavedStateRegistryOwner lifecycle. So if the activity is finished, so is SavedInstanceState