1

有没有办法在 Koin 上实现 Dagger 的 SubCompoent 概念?

我想做的事情是使用父范围的实例。

app_modules.kt

val favoriteModule = module {
    scope(named<FavoriteFragment>()) {
        scoped { GetFavoriteMovies(get()) }
        scoped { FavoriteVMFactory(get(), get()) } // This need 'MovieEntityMovieMapper'
    }
}

val popularModule = module {
    scope(named<PopularFragment>()) {
        scoped { GetPopularMovies(get()) }
        scoped { PopularVMFactory(get(), get()) } // This need 'MovieEntityMovieMapper'
    }
}

val searchModule = module {
    scope(named<SearchFragment>()) {
        scoped { SearchMovies(get()) }
        scoped { SearchVMFactory(get(), get()) } // This need 'MovieEntityMovieMapper'
    }
}

val mainModule = module {
    scope(named<MainActivity>()) {
        scoped { MovieEntityMovieMapper() }
        // this ImageLoader also injected by Fragments
        scoped<ImageLoader> { (activity: Activity) -> GlideImageLoader(activity) }
    }
}

使用 Dagger,这可以通过 SubComponent 或 Component Dependency 来完成。

但是在 Koin(尤其是 2.0)中,我找不到路。

有人回答说 use GlobalContext.get().koin.getScope("Parent").get<>()

https://github.com/InsertKoinIO/koin/issues/513

Koin 在模块之间共享实例

但我认为这不是一种干净的方法和依赖注入。

4

1 回答 1

0

You can try https://github.com/beyama/winter which is inspired by Koin but has child graphs that can be used like Dagger's subcomponents. Winter has been used in production for some major apps with several million installs for a few years now. I hope it is ok to post an example here: https://play.google.com/store/apps/details?id=de.prosiebensat1digital.seventv Disclaimer: I know the author and have been using his library myself since its release. So far it has been stable in my experience.

于 2020-05-14T08:21:36.887 回答