0

根据本教程使用 Dagger Hilt 添加子组件需要

@Singleton
class UserManager @Inject constructor(
    // Since UserManager will be in charge of managing the UserComponent's
    // lifecycle, it needs to know how to create instances of it. We use the
    // provider (i.e. factory) Dagger generates for us to create instances of UserComponent.
    private val userComponentProvider: Provider<UserComponent.Builder>
) {

  /**
   *  UserComponent is specific to a logged in user. Holds an instance of
   *  UserComponent. This determines if the user is logged in or not, when the
   *  user logs in, a new Component will be created.
   *  When the user logs out, this will be null.
   */
  var userComponent: UserComponent? = null
      private set

  ...

  private fun userLoggedIn(userId: String) {
    // When the user logs in, we create a new instance of UserComponent
    val user = createUser(userId)
    userComponent = userComponentProvider.get().setUser(user).build()
  }

  private fun logout() {
    // When the user logs out, we remove the instance of UserComponent from memory
    userComponent = null
  }
}

这就是您创建子组件的方式userComponent = userComponentProvider.get().setUser(user).build()

我的问题是如何实施Provider

private val userComponentProvider: Provider<UserComponent.Builder>

因为它没有显示它是如何提供给 UserManager 类的

我正在尝试创建一个 AppComponent 来测试子组件如何与 Dagger Hilt 一起使用

@DefineComponent(parent = ApplicationComponent::class)
interface AppComponent {

    @DefineComponent.Builder
    interface Builder {
        fun application(@BindsInstance application: Application): Builder
        fun build(): AppComponent
    }

}

并在应用中

@HiltAndroidApp
class MyApplication : Application() {

    private val appComponentProvider by lazy {
        object : Provider<AppComponent.Builder> {
            override fun get(): AppComponent.Builder {
                ??????
            }

        }
    }

    val appComponent by lazy {
        appComponentProvider.get().application(this).build()
    }
    
}

我应该如何在里面创建构建器get(),创建实现 Provider 的匿名类不是正确的吗?

4

1 回答 1

1

我的问题是如何实现 Provider

您不必Provider自己实现——Dagger 知道如何自动创建任何绑定的提供者。因此,在您的情况下,您应该将提供程序注入您的应用程序:

@HiltAndroidApp
class MyApplication: Application() {
  @Inject lateinit var provider: Provider<MySubcomponent.Builder>

  val mySubcomponent by lazy {
      provider.get()....build()
  }  
}
于 2020-07-26T18:45:43.843 回答