Hi, Is it possible to share the same instance of a...
# koin
y
Hi, Is it possible to share the same instance of a ViewModel between Compose screens?
a
ViewModel is backed by Activity or Fragment ... then yes
j
To add on what @arnaud.giuliani has said, yes you can with dependencies in Composable screens(ie. One Activity with Multiple Composable Screens)
👍 1
y
Are there any examples how it can be done?
a
for viewModel you can use
koinViewModel
function
y
@arnaud.giuliani I tried it, and each time a new instance is created. Below is the code showing how I do it and the
RegistrationViewModel
is not shared between screens. What am I missing to achieve the result that this
ViewModel
will be the same between screens? 😄 Here is entry screen:
Copy code
composable(EMAIL_ROUTE) {
    val vm: RegistrationViewModel = koinViewModel<RegistrationViewModel>()
    val state = vm.registrationState.collectAsState()

    EmailScreen(
        registrationState = state.value,
        onNavigateBack = onNavigateBack,
        onNextClicked = onNextClicked,
        onEmailValueChange = vm::onEmailEnter,
    )
}
And Here is my next screen that I'm navigating from
EmailScreen
Copy code
composable(PASSWORD_ROUTE) {
    val vm: RegistrationViewModel = koinViewModel<RegistrationViewModel>()
    val state = vm.registrationState.collectAsState()

    PasswordScreen(
        registrationState = state.value,
        onNavigateBack = onNavigateBack,
        onPasswordChange = vm::onPasswordEnter,
        onCreateAccount = onCreateAccount,
    )
}
1
a
yes a patch is available in 3.5.4-RC1 for that ViewModel recreation issue