Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!