ScreenModel¶
Success
The ScreenModel API is a part of the modulecafe.adriel.voyager:voyager-screenmodel
(see Setup).
ScreenModel
is just like a ViewModel: designed to store and manage UI-related data in a lifecycle conscious way. It also allows data to survive configuration changes such as screen rotations.
Unlike ViewModel
, ScreenModel
is just an interface. It’s also Android independent and doesn’t requires an Activity
or Fragment
to work.
class HomeScreenModel : ScreenModel {
// Optional
override fun onDispose() {
// ...
}
}
By design, it’s only possible to create a ScreenModel
instance inside a Screen
. Call rememberScreenModel
and provide a factory lambda.
class HomeScreen : Screen {
@Composable
override fun Content() {
val screenModel = rememberScreenModel { HomeScreenModel() }
// ...
}
}
If you need to have multiple instances of the same ScreenModel
for the same Screen
, add a tag to differentiate them.
val screenModel = rememberScreenModel(tag = "CUSTOM_TAG") { HomeScreenModel() }
Sample¶
Info
Source code here.
Navigator scoped ScreenModel¶
Success
TherememberNavigatorScreenModel
are part of the navigator library.
Starting from 1.0.0rc08
by using the new Navigator extension called rememberNavigatorScreenModel
is possible to have a ScreenModel that is shared cross all Screens from a Navigator and when the Navigator leaves the Composition the ScreenModel is disposed.
class HomeScreen : Screen {
@Composable
override fun Content() {
val navigator = LocalNavigator.currentOrThrow
val screenModel = navigator.rememberNavigatorScreenModel { HomeScreenModel() }
// ...
}
}