如何为许多片段创建ViewModel实例?
我的活动中有很多片段,每种片段都使用VM中的方法。在每个片段中,我都必须在以这种方式使用它之前创建ViewModel实例:
val retrofitService = RetrofitService.getInstance(requireContext())
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(
this@FragmentName,
AppVMFactory(mainRepository)
).get(AppViewModel::class.java)
在我的Mainrepository中,我有我的请求方法:
class MainRepository constructor(private val retrofitService: RetrofitService) {
suspend fun someMethod() = retrofitService.someMethod()
}
在改造服务中,我有API请求方法。主要问题是我如何仅一次不使用此代码来创建ViewModel实例:
val retrofitService = RetrofitService.getInstance(requireContext())
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(
this@FragmentName,
AppVMFactory(mainRepository)
).get(AppViewModel::class.java)
在每个片段中。一开始,我考虑了单个片段父母,但是我不确定对话范围是否可以以及如何与数据绑定一起使用。也许我可以使用我不知道的Android开发的某些功能?
I have a lot of fragments in my activity, each of which uses own methods in the VM. In each of fragment I have to create viewmodel instance before using it in such way:
val retrofitService = RetrofitService.getInstance(requireContext())
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(
this@FragmentName,
AppVMFactory(mainRepository)
).get(AppViewModel::class.java)
in my MainRepository I have my requests methods:
class MainRepository constructor(private val retrofitService: RetrofitService) {
suspend fun someMethod() = retrofitService.someMethod()
}
and in retrofit service I have api requests methods. The main question is how I cane create viewModel instance only one time without using this code:
val retrofitService = RetrofitService.getInstance(requireContext())
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(
this@FragmentName,
AppVMFactory(mainRepository)
).get(AppViewModel::class.java)
in each fragment. At the beginning I thought about single fragment parent, but I'm not sure whether it will be ok for dialogFragment and also how it will be able to use with data binding. Maybe I can use some features of android development about which I don't know?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用sharedViewModel,并且将在活动中的所有片段中共享 https:/// developer.android.com/topic/libraries/architecture/viewmodel#sharing
You can use sharedViewModel and it will be shared across all fragments in activity https://developer.android.com/topic/libraries/architecture/viewmodel#sharing