josephwj
josephwj

Reputation: 45

ViewModel being recreated on configuration change (screen orientation/rotation)

I'm pretty new to Jetpack Compose, and I'm really struggling with having a persisting viewModel whenever a reconfiguration occurs, like rotating the screen.

It worked for a simpler app where the viewModel was instantiated directly (it didn't need any inputs). The viewmodel would be created the first time when the app first starts; and then screen orienting, etc. does not cause the viewModel to be recreated.

However, when trying to set it up for viewmodels that require input, using the viewmodel factory, it seems to always re-instantiate on config changes.

What I'm wondering is, why does this persist on reconfiguration:

// (in onCreate)
val exampleViewModel: ExampleViewModel = viewModel()

But this doesn't (and how to make it persist?):

// (in onCreate)
val owner = LocalViewModelStoreOwner.current
val application: Application = LocalContext.current.applicationContext as Application
val exampleViewModel: ExampleViewModel = viewModel(owner, "ExampleViewModel", ExampleViewModelFactory(application))

...

// (class ExampleViewModelFactory(val application: Application): ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass : Class<t>) : T {
        return ExampleViewModel(application) as T
    }
}

Upvotes: 1

Views: 448

Answers (0)

Related Questions