Koin: How to inject parent fragment's viewModel in 2.1.0

Created on 25 Feb 2020  路  2Comments  路  Source: InsertKoinIO/koin

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?

Most helpful comment

Hi, try this one:

private val viewModel by lazy { 
     requireParentFragment().getViewModel<MyViewModel>()
} 

More info here: https://github.com/InsertKoinIO/koin/issues/593

All 2 comments

Hi, try this one:

private val viewModel by lazy { 
     requireParentFragment().getViewModel<MyViewModel>()
} 

More info here: https://github.com/InsertKoinIO/koin/issues/593

Was this page helpful?
0 / 5 - 0 ratings

Related issues

erikhuizinga picture erikhuizinga  路  3Comments

luna-vulpo picture luna-vulpo  路  4Comments

pchmielowski picture pchmielowski  路  3Comments

TedHoryczun picture TedHoryczun  路  4Comments

hkelidari picture hkelidari  路  3Comments