I want to migrate from Koin 2.0.1 to 2.1.0 but there is a use case which I do not know how to migrate.
I have several fragments nested in a parent fragment and I want these nested fragments to use parent fragment's ViewModel for communication.
In 2.0.1 I did it like this:
class NestedFragment: Fragment() {
private val sharedViewModel by sharedViewModel<ParentViewModel>(from = {
parentFragment
?: throw IllegalStateException(
"NestedFragment needs a parentFragment to work properly with ParentViewModel"
)
})
}
But I noticed that in 2.1.0 there is no version of sharedViewModel with parameter from.
The only way I found how to use an alternative ViewModelStoreOwner is to use it directly like this:
private val sharedViewModel by lazy<ParentViewModel> {
(parentFragment
?: throw IllegalStateException(
"NestedFragment needs a parentFragment to work properly with ParentViewModel"
)).getViewModel()
}
But that looks very ugly.
Is there a better way of injecting the parent fragment's view model that I am not aware of?
Hi, try this one:
private val viewModel by lazy {
requireParentFragment().getViewModel<MyViewModel>()
}
More info here: https://github.com/InsertKoinIO/koin/issues/593
Duplicate of https://github.com/InsertKoinIO/koin/issues/593
Most helpful comment
Hi, try this one:
More info here: https://github.com/InsertKoinIO/koin/issues/593