https://kotlinlang.org logo
Title
b

bharath

08/10/2022, 6:37 AM
Hey guys, i have added
viewModel { 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?
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
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
setContent {
    //Injecting via Koin DI and in compose way
    val mainViewModel = getViewModel<MainViewModel>()
mainViewModel.test.value = Test(true)
}
now in my home composable when i inject the same viewmodel
@RootNavGraph(start = true)
@Destination(
    route = Constants.NavigationRoutes.HOME
)
@Composable
fun HomeContent(){
    val mainViewModel = getViewModel<MainViewModel>()
Timber.d("MainViewmodel state ${mainViewModel.test.value} }")
}
Here i am getting null here for the test value
is it possible to have the viewmodel reference injected with same instance in many composable without passing the reference via its constructor?
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.
b

bharath

08/10/2022, 8:32 AM
so is there a way we can inject shared viewmodel in composables like we do with fragments and actiivty similar to this private val viewModel by sharedViewModel<YourViewModel>()?
c

curioustechizen

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