【问题标题】:How can I return a component from Application to module?如何将组件从应用程序返回到模块?
【发布时间】:2020-10-08 16:49:06
【问题描述】:

尝试理解以下example并做类似的事情。

在我的应用程序中有一个模块,我想在其中使用 Dagger。 为此,我需要一个 Application 类,我在其中初始化并存储 AppComponent

从文档来看,我需要使用我的模块中的组件创建一个接口:

interface PasscodeSetupComponentProvider {
    fun providePasscodeSetupComponent(): PasscodeComponent
}

然后我将为我的Application类实现这个接口:

open class FenturyApplication : PasscodeSetupComponentProvider {

    lateinit var appComponent: AppComponent

    override fun onCreate() {
        super.onCreate()
        appComponent = DaggerAppComponent.builder()
            .appModule(AppModule(applicationContext))
            .build()
    }

    override fun providePasscodeSetupComponent(): PasscodeComponent {
        return appComponent.passcodeComponent
    }
}

但从文档中的示例来看,我不明白我的界面 AppcomponentpasscodeComponent 应该是什么。

在示例中,它看起来像这样:

class MyApplication: Application(), LoginComponentProvider {
  // Reference to the application graph that is used across the whole app
  val appComponent = DaggerApplicationComponent.create()

  override fun provideLoginComponent(): LoginComponent {
    return appComponent.loginComponent().create()
  }
}

我在我的 AppComponent 中添加了以下代码:

@Component(modules = [AppModule::class])
@Singleton
interface AppComponent {
    val applicationContext: Context
    fun passcodeComponent(): PasscodeComponent
}

如果我理解正确,那么在我模块中的片段中,我可以编写以下内容:

lateinit var passcodeComponent: PasscodeComponent

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val context = activity?.applicationContext ?: return
    passcodeComponent = (context as PasscodeSetupComponentProvider).providePasscodeSetupComponent()
    passcodeComponent.inject(this)

之后我希望我可以在我的模块中使用匕首。

【问题讨论】:

    标签: android kotlin dependency-injection dagger-2 android-module


    【解决方案1】:

    您错过了 AppComponent 编写方式的关键部分。您可以在this链接中阅读完整的代码。

    请注意 Google 如何声明 LoginComponent(作为子组件)以及他们如何在 AppComponent 中声明它以便返回一个新的 LoginComponent 实例。

    AppComponent(复制自我发布的链接)

    @Singleton
    @Component(modules = [NetworkModule::class, SubcomponentsModule::class])
    interface ApplicationComponent {
    // This function exposes the LoginComponent Factory out of the graph so consumers
    // can use it to obtain new instances of LoginComponent
    fun loginComponent(): LoginComponent.Factory
    }
    
    

    以及 LoginComponent 的代码

    @Subcomponent
    interface LoginComponent {
    
        // Factory that is used to create instances of this subcomponent
        @Subcomponent.Factory
        interface Factory {
            fun create(): LoginComponent
        }
    
        fun inject(loginActivity: LoginActivity)
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 2021-08-18
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多