android - 我不明白如何在我的 Interactor 类中注入 Retrofit 对象
问题描述
我试图阅读一堆文章,但我仍然无法掌握匕首的想法。
我有我想要注入改造实例的指标类。
public class GetForecastInteractorImpl implements MainContract.GetForecastInteractor {
@Inject
Retrofit retrofit;
...
}
没有问题,我能够将它注入 MainActivity,但这不是我想要的。
任何想法?我不知道代码的哪些部分会有所帮助,所以请告诉我我会提供它们。
解决方案
对于注入,您必须遵循以下过程,让我们以提供 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,然后您可以继续使用该改造。
让我知道我是否能够解决您的评论:)
推荐阅读
- python - 切换到 Python/Selenium 后无法与 iframe 交互
- jquery - 跟踪jquery ui中的可拖动div?
- c++ - 已知类名的 C++ 模板友元声明嵌套在任何其他
- sql - 优化的 SQL 选择,用于跨多个表进行选择
- kotlin - subscribeOn(Schedulers.io()) 不工作,但 subscribeOn(Schedulers.trampoline()) 不工作
- docker - 为什么我的 Docker 容器没有运行我的 cron 脚本,但是当我重新启动服务 cron 时它运行了?
- java - 如何创建带有圆角背景的 EditText
- ios - 在 pubspec.yaml 中添加 Google Maps 包后,Flutter iOS 应用程序将无法构建
- scala - Scala中具有相互递归类型的递归方案
- python-3.x - 使用 Selenium 和 Python 找不到 css 选择器、方法或元素错误