首页 > 解决方案 > 我不明白如何在我的 Interactor 类中注入 Retrofit 对象

问题描述

我试图阅读一堆文章,但我仍然无法掌握匕首的想法。

我有我想要注入改造实例的指标类。

public class GetForecastInteractorImpl implements MainContract.GetForecastInteractor {

@Inject
Retrofit retrofit;
...
}

没有问题,我能够将它注入 MainActivity,但这不是我想要的。

任何想法?我不知道代码的哪些部分会有所帮助,所以请告诉我我会提供它们。

标签: androidretrofitdaggerandroid-mvp

解决方案


对于注入,您必须遵循以下过程,让我们以提供 Retrofit 为例(以 Kotlin 作为参考) 1. 创建 NetModule(用 @Module 注释)

创建改造你可能需要提供 OkHttpClient

@Provides
@Singleton(because we need only one instance through out the application)
fun provideOkHttpClient(): OkHttpClient {
return OkHttpClient().Builder().build() (you can also pass other things while building like Interceptor, timeOut check docs for that)
}

现在使用相同的格式提供改造,但要创建改造,您需要将 OkHttpClient 作为我们在上面提供的参数传递。

@Provides
    @Singleton
    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
    return Retrofit.Builder().client(okHttpClient).build()
    }

现在您必须通过提供上面的 NetModule() 创建使用 @Component 注释的应用程序组件

编译 Dagger 后将生成该组件类,您可以使用它来注入您的类

在上述情况下,假设我们创建 AppComponent 的地方有 MainApplication 类,有一个名为 MainActivity 的活动需要 Retrofit 实例,然后 MainActivityComponent 将添加依赖项,说我也需要 AppComponent,然后您可以继续使用该改造。

让我知道我是否能够解决您的评论:)


推荐阅读