bharath
08/10/2022, 6:37 AMviewModel { MainViewModel() }
in koin module and injecting the view model with
val mainViewModel: MainViewModel by viewModel()
val mainViewModel2 = getViewModel<MainViewModel>()
these both ways and setting value in one composable, and injected the same viewmodel in similar way in other composable, but instead of returning the existing instance it always returns new instance of that view model in the composable, can anyone help me with this?curioustechizen
08/10/2022, 7:56 AMbharath
08/10/2022, 8:02 AMdata class Test(val isSomething:Boolean)
class MainViewModel() :ViewModel(),
KoinComponent {
var test = mutableStateOf<Test?>(null)
}
class KoinCoreModule {
val koinCoreModule = module {
viewModel { MainViewModel() }
}
bharath
08/10/2022, 8:03 AMsetContent {
//Injecting via Koin DI and in compose way
val mainViewModel = getViewModel<MainViewModel>()
mainViewModel.test.value = Test(true)
}
curioustechizen
08/10/2022, 8:19 AMviewModel
DSL of Koin uses factory{}
under the hood. This means by default you get a new instance every time you inject it; unless your are in the same scope as a previously obtained instance (I might have absolutely murdered the definition there).
In your case your MainActivity and HomeContent each have their own owners so you'll get different instances when you inject into them. What you are actually looking for is a shared ViewModel.
I'm not entirely sure how you would implement that for your usecase though.curioustechizen
08/10/2022, 8:35 AMbharath
08/10/2022, 9:19 AM