InsertKoinIO / koin

Koin - a pragmatic lightweight dependency injection framework for Kotlin & Kotlin Multiplatform
https://insert-koin.io
Apache License 2.0
8.98k stars 710 forks source link

Allow lazy providing the ViewModelStoreOwner for the getLazyViewModelForClass extension #1774

Closed NinoDLC closed 2 months ago

NinoDLC commented 8 months ago

Is your feature request related to a problem? Please describe. It's currently impossible to use the getViewModelForClass function (as of Koin 3.5.3) in a custom view trying to inject its ViewModel, while it seems this API is designed for such usecase.

This code crashes at runtime when the Activity or Fragment's XML using this custom view is inflated:

class FooCustomView(context: Context, attrs: AttributeSet? = null) : TextView(context, attrs) {
    private val viewModel: FooViewModel by getLazyViewModelForClass(
        clazz = FooViewModel::class, 
        owner = findViewTreeViewModelStoreOwner()!!, // <-- Will always crash there
    )
}

Describe the solution you'd like The resolution of the ViewModelStoreOwner should be lazy because in this usecase (injecting a ViewModel to a custom view), the ViewModelStoreOwner is not available immediately (during the inflation of the View).

Describe alternatives you've considered For the moment, I'm doubling down on the lazy but that's obviously just an (ugly) patch until a PR provides true laziness:

inline fun <reified T : ViewModel> View.customViewLazyViewModel(): Lazy<T> = lazy {
    getLazyViewModelForClass(
        clazz = T::class,
        owner = findViewTreeViewModelStoreOwner()!!,
    ).value
}

Target Koin project androidx

stale[bot] commented 3 months ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.