Lea*_*ira 13 android dependency-injection kotlin dagger-2
我正在研究Dagger 2 for DI,我只是做了这个代码来注入Retrofit:
NetModule.kt
@Module
class NetModule(val baseUrl: String) {
@Provides
@Singleton
fun provideRetrofit() : Retrofit{
[some logic here]
}
}
Run Code Online (Sandbox Code Playgroud)
AppModule.kt
@Module
class AppModule(val mApplication: Application) {
@Provides
@Singleton
fun provideApplication() : Application{
return mApplication
}
}
Run Code Online (Sandbox Code Playgroud)
NetComponent.kt:
@Singleton
@Component(modules = arrayOf(AppModule::class, NetModule::class))
interface NetComponent {
fun inject(activity: Activity)
}
Run Code Online (Sandbox Code Playgroud)
CustomApplication.kt
class CustomApplication : Application() {
companion object {
lateinit var mNetComponent: NetComponent
}
override fun onCreate() {
super.onCreate()
AndroidThreeTen.init(this)
mNetComponent = DaggerNetComponent.builder()
.appModule(AppModule(this))
.netModule(NetModule(getString(R.string.api_base_url)))
.build()
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的活动中:
class TrashCansInfoActivity : AppCompatActivity(){
@Inject
lateinit var mRetrofit: Retrofit
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_trash_cans_info)
CustomApplication.mNetComponent.inject(this)
setSupportActionBar(toolbar)
populateTrashCanList()
}
private fun populateTrashCanList(){
showProgress(true)
mRetrofit.create(ApiClient::class.java)
.getTrashCans()
.map { it.map { it.toTrashCan() } }
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.doOnError {
showProgress(false)
Toast.makeText(this, "Erro ao carregar lista de lixeiras", Toast.LENGTH_SHORT).show()
}.doOnCompleted { showProgress(false) }
.subscribe(behaviorSubject)
}
}
Run Code Online (Sandbox Code Playgroud)
所以,这段代码应该可行,对吧?应该添加依赖...但是当我运行我的应用程序时...我明白了:
kotlin.UninitializedPropertyAccessException: lateinit property mRetrofit has not been initialized
Run Code Online (Sandbox Code Playgroud)
所以Retrofit没有被注入.我错过了什么?
欢迎任何帮助!
Epi*_*rce 19
fun inject(activity: Activity)
Run Code Online (Sandbox Code Playgroud)
应该
fun inject(activity: TrashCansInfoActivity)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6606 次 |
| 最近记录: |