Hey guys, i have added ```viewModel { MainViewMode...
# koin
b
Hey guys, i have added
Copy code
viewModel { MainViewModel() }
in koin module and injecting the view model with
Copy code
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?
c
Can you clarify what you mean by it always returns a new instance of that ViewModel? What is your expectation?
b
for eg: lets say i have a main viewmodel
Copy code
data class Test(val isSomething:Boolean)

class MainViewModel() :ViewModel(),
    KoinComponent {
    var test = mutableStateOf<Test?>(null)
}
class KoinCoreModule {
    val koinCoreModule = module {
viewModel { MainViewModel() }
}
now in mainactivity in setcontent i am injecting and setting the test value of that viewmodel
Copy code
setContent {
    //Injecting via Koin DI and in compose way
    val mainViewModel = getViewModel<MainViewModel>()
mainViewModel.test.value = Test(true)
}
c
The
viewModel
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.
Please keep the conversation in this thread instead of "Send to channel" every time. It is definitely possible to inject shared viewmodels. I've done it with navgraph scoped viewModels. However in your case you want to share a ViewModel between an Activity and a Composable. I think it should be possible but I don't know how.
b
oh ok, thank you so much for your replies