嗨,我有一个 ViewModel,它有两个使用 Dagger 2.11 注入的 var。
然而,它永远不会被注入到我的 viewModel 中,而在我的应用程序的其他任何地方,这些相同的依赖 Vars 都会被初始化并完美注入
下面是我的视图模型
class MyViewModel : AndroidViewModel, MyViewModelContract {
private lateinit var pointsBalance: MutableLiveData<PointsBalance>
@Inject
lateinit var accountDelegator: AccountDelegatorContract
@Inject
constructor(application: Application) : super(application)
init {
DaggerApplicationComponent.builder().application(getApplication() as MyApplication).build().inject(this)
}
override fun getPointsBalance(): LiveData<PointsBalance> {
if (!this::pointsBalance.isInitialized) {
//get balance from network api etc
}
return pointsBalance
}
accountDelegator 抱怨没有初始化
下面是我如何在 MyModule.class 中绑定这个 viewModel
@Provides
@JvmStatic
@Singleton
fun providesViewModel(viewModel: MyViewModel): MyViewModelContract = viewModel
我的自定义应用程序
class MyApplication : DaggerApplication() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
val applicationComponent = DaggerApplicationComponent.builder()
.application(this)
.build()
applicationComponent.inject(this)
return applicationComponent
}
}
我的应用组件
@Singleton
@Component(modules = arrayOf(MyModule::class,
))
interface ApplicationComponent : AndroidInjector<DaggerApplication> {
fun inject(mApplication: MyApplication)
override fun inject(instance: DaggerApplication)
@Component.Builder
interface Builder {
@BindsInstance
fun application(applicaton: MyApplication): Builder
fun build(): ApplicationComponent
}
}
我如何在活动/片段中使用此视图模型
viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)