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

bharath

08/10/2022, 6:37 AM
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

curioustechizen

08/10/2022, 7:56 AM
Can you clarify what you mean by it always returns a new instance of that ViewModel? What is your expectation?
b

bharath

08/10/2022, 8:02 AM
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

curioustechizen

08/10/2022, 8:19 AM
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

bharath

08/10/2022, 9:19 AM
oh ok, thank you so much for your replies
33 Views