Android ViewModel
To use the AndroidScreen you should first import cafe.adriel.voyager:voyager-androidx (see Setup).
If you're using ViewModel from AndroidX then you should use AndroidScreen or implement the ScreenLifecycleProvider interface.
1
class PostListScreen : AndroidScreen() {
2
3
@Composable
4
override fun Content() {
5
val viewModel = viewModel<PostListViewModel>()
6
// ...
7
}
8
}
Copied!
The AndroidScreen provides its own LocalViewModelStoreOwner and LocalSavedStateRegistryOwner, that way you can safetily create ViewModels without depending on Activity or Fragment.
Voyager provides a similar implementation, the ScreenModel, which does the same (and more!) as ViewModel.

Manual integration

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.
1
class PostListScreen : Screen, ScreenLifecycleProvider {
2
3
override fun getLifecycleOwner() =
4
AndroidScreenLifecycleOwner.get(key)
5
6
@Composable
7
override fun Content() {
8
// ...
9
}
10
}
Copied!

Sample

Source code here.
Last modified 2mo ago
Copy link