2
我學習匕首2 DI,我只是做了這個代碼注入改造:匕首+科特林不注射
NetModule.kt
@Module
class AppModule(val mApplication: Application) {
@Provides
@Singleton
fun provideApplication() : Application{
return mApplication
}
}
AppModule.kt
@Module
class AppModule(val mApplication: Application) {
@Provides
@Singleton
fun provideApplication() : Application{
return mApplication
}
}
NetComponent .kt:
@Singleton
@Component(modules = arrayOf(AppModule::class, NetModule::class))
interface NetComponent {
fun inject(activity: Activity)
}
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()
}
}
然後在我的活動:
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)
}
}
所以,這個代碼應該工作,對不對?應該添加的依賴...但是,當我運行我的應用程序...我得到這個:
kotlin.UninitializedPropertyAccessException: lateinit property mRetrofit has not been initialized
因此,改造沒有被注入。我錯過了什麼?
歡迎任何幫助!
它的工作。謝謝! –