Android ViewModel
If you're using ViewModel from AndroidX then you should use
AndroidScreen
or implement the ScreenLifecycleProvider
interface. class PostListScreen : AndroidScreen() {
@Composable
override fun Content() {
val viewModel = viewModel<PostListViewModel>()
// ...
}
}
The
AndroidScreen
provides its own LocalViewModelStoreOwner
and LocalSavedStateRegistryOwner
, that way you can safetily create ViewModel
s without depending on Activity
or Fragment
.Voyager provides a similar implementation, the ScreenModel, which does the same as
ViewModel
but also works with Compose Multiplatform.If you don't want to inherit from an abstract class, no problem. You can easily make your screens compatible with
ViewModel
by implementing the ScreenLifecycleProvider
interface.class PostListScreen : Screen, ScreenLifecycleProvider {
override fun getLifecycleOwner() =
AndroidScreenLifecycleOwner.get(key)
@Composable
override fun Content() {
// ...
}
}

Last modified 1yr ago