我如何在模块中添加视图模型? [英] How i can add view model in module?
本文介绍了我如何在模块中添加视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Dagger中,如何向模块添加模型? 例如,我通过以下方式添加了演示者:
In Dagger, how can I add a model to Module? For example I added the presenter in the following way:
@Module
class AboutModule(val appContext: Context) {
@FragmentScope
@Provides
fun providePresenter(): AboutListContract.Presenter {
return AboutListPresenter(appContext = appContext)
}
}
现在,我想添加我的View模型以及appContext.
Now i want want to add my View model, also with appContext.
class AboutViewModel(val appContext: Context): ViewModel() {
更新: 我可以这样添加视图模型吗?
UPDATE: Can i add my view model smth like this?
@Module
class AboutModule(val appContext: Context) {
@FragmentScope
@Provides
fun provideModel(model: AboutViewModel): ViewModel {
return AboutViewModel(appContext = appContext)
}
}
推荐答案
我用下一个解决方案解决了我的问题:
I solved my problem with next solution:
@Module
class AboutModule(val appContext: Context) {
@FragmentScope
@Provides
fun provideFactory(): AboutViewModelFactory {
return AboutViewModelFactory(appContext)
}
}
在片段中这样写: class AboutFragment:BaseFragment(),OnItemClickListener {
And in fragment write smth like this: class AboutFragment : BaseFragment(), OnItemClickListener {
lateinit var viewModel: AboutViewModel
@Inject lateinit var viewModelFactory: AboutViewModelFactory
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectDependencies()
viewModel = ViewModelProviders
.of(this, viewModelFactory)
.get(AboutViewModel::class.java)
}
private fun injectDependencies() {
activity?.let {
DaggerAboutComponent.builder().aboutModule(AboutModule(it)).build().inject(this)
}
}
很好的建议: https://stackoverflow.com/a/60884492/6387618
这篇关于我如何在模块中添加视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文