Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

393
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda