How to make viewModel lifecycle work for AndroidX-Lifecycle-viewModel-SavedState (with Jetpack Compose)?

698 views Asked by At

My setup (relevant subset):

  • Android Gradle Plugin 7.1.2
  • androidx.lifecycle:lifecycle-viewmodel-savedstate 2.4.1
  • androidx.activity:activity-compose 1.4.0
  • androidx.compose.* 1.2.0-alpha04
  • androidx.navigation:navigation-compose 2.4.1

I am trying to persist UI state by enhancing the capabilities of my activity-bound ViewModel to leverage lifecycle-viewmodel-savedstate. Basically it looks like this:

class MySavedStateViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() { 

   init {
       viewModelScope.launch {
           // Logic to load data from savedStateHandle
       }
   } 

   fun saveData() {
       // Logic to save data to savedStateHandle
   }

}

I create the ViewModel within a composable, which looks like this:

val mySavedStateViewModel: MySavedStateViewModel by activityBoundViewModel(
     factoryProducer = {
        MySavedStateViewModelFactory(context as ComponentActivity)
     }
)

MySavedStateViewModelFactory looks like this:

class MySavedStateViewModelFactory(
    savedStateRegistryOwner: SavedStateRegistryOwner,
    bundle: Bundle? = null
) :
    MySavedStateViewModelFactory(savedStateRegistryOwner, bundle) {

    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(key: String, modelClass: Class<T>, handle: SavedStateHandle): T {
        val viewModel = MySavedStateViewModel(savedStateHandle = handle)
        return viewModel as T
    }

}

It looks like savedStateHandle is updated properly when using the app but when I kill it and start it again the data is lost.

What do I need to change to make persistance work?

Related but an old post: SavedState ViewModel Using SavedStateViewModelFactory

0

There are 0 answers