Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

392
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda