https://kotlinlang.org logo
#koin
Title
# koin
y

ynsok

03/07/2024, 1:06 PM
Hi, Is it possible to share the same instance of a ViewModel between Compose screens?
a

arnaud.giuliani

03/08/2024, 8:06 AM
ViewModel is backed by Activity or Fragment ... then yes
j

Joel Crawford

03/08/2024, 10:25 AM
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

ynsok

03/09/2024, 9:28 AM
Are there any examples how it can be done?
a

arnaud.giuliani

03/11/2024, 4:19 PM
for viewModel you can use
koinViewModel
function
y

ynsok

03/12/2024, 8:07 PM
@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

arnaud.giuliani

03/13/2024, 8:04 AM
yes a patch is available in 3.5.4-RC1 for that ViewModel recreation issue