最近我开始将我们的应用程序分成更小的 Android 模块,但我很难让 Dagger 以我想要的方式工作。
我目前的 Dagger 设置包括:
- ApplicationComponent
标记为@Singleton
。此组件在应用启动时创建。
- UserSubComponent
标有@UserScope
。该子组件在用户登录时创建。
这两个组件与负责创建这两个组件的 App
类一起放置在我的 app
模块中。
在我的 login
模块中(它是我的应用程序模块的父级,因此它无法访问应用程序模块中的任何内容)我有我的 AuthenticationManager
。
当用户登录时,我使用 RxJava 从我的 AuthenticationManager
向 App
发出信号,因此可以创建 UserSubComponent
。
我的问题是我需要从我的 UserSubComponent
访问一些依赖项,在它创建之后,在我的 AuthenticationManager
中,这样我就可以在继续之前预加载用户的数据.
模块结构:
app (AppComponent & UserSubComponent)
^
|
login (AuthenticationManager) - feature 2 - feature 3
我的应用类:
class App : DaggerApplication() {
@Inject
lateinit var authenticationManager: AuthenticationManager
override fun onCreate() {
super.onCreate()
authenticationManager
.authenticationStateStream
.subscribe { state ->
if (state == AuthenticationState.AUTHENTICATED) {
AppInjector.userComponent.inject(this)
}
}
}
身份验证管理器:
class AuthenticationManager @Inject constructor(loginApi: LoginApi) {
@Inject
lateinit var preLoader : PreLoader // This won't work because of different scope
val authenticationStateStream = Observable<AuthenticationState>()
fun login() {
if (success) {
authenticationStateStream.emit(AuthenticationState.AUTHENTICATED)
// UserSubComponent is now created
preLoader.preload()
}
}
}
应用组件
@Singleton
@Component(modules = [AppModule::class, AndroidSupportInjectionModule::class])
interface AppComponent : AndroidInjector<App> {
fun userComponentBuilder(): UserComponent.Builder
}
应用模块
@Module
class AppModule {
@Provides
@Singleton
fun provideLoginApi() = LoginApi()
}
用户子组件
@UserScope
@Subcomponent(modules = [UserModule::class, AndroidSupportInjectionModule::class])
interface UserComponent : AndroidInjector<App> {
@Subcomponent.Builder
interface Builder {
fun build(): UserComponent
}
}
用户模块
@Module
class UserModule {
@Provides
@UserScope
fun providesPreLoader() = PreLoader()
}
我能否以某种方式让这个结构发挥作用?或者,当涉及到模块 + Dagger 时,我有哪些选择?
最佳答案
经过多次尝试,我终于设法解决了我的问题。
我发现的是:
- 当您的应用分为多个模块时,请勿使用子组件。
- 每个模块都需要它自己的组件(功能组件)
我发现这篇文章非常有用: https://proandroiddev.com/using-dagger-in-a-multi-module-project-1e6af8f06ffc
关于android - 从父 android 模块访问 Dagger 子组件依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53653653/