[英]Android ViewModelProvider() parameter error
I am trying to get a value from the SharedViewModel class but the ViewModelProvider() is giving a parameter error when i am passing requireActivity() although the same initilization and assignment works in my fragments.我试图从 SharedViewModel class 中获取一个值,但是当我传递 requireActivity() 时 ViewModelProvider() 给出了一个参数错误,尽管我的片段中使用了相同的初始化和分配。
It is requiring "ViewModelStoreOwner" to be passed.它要求传递“ViewModelStoreOwner”。
class CourseRepository(val app: Application) {
private var viewModel: SharedViewModel = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
val courseData = MutableLiveData<List<Course>>()
init {
CoroutineScope(Dispatchers.IO).launch {
callWebService()
}
}
@WorkerThread
suspend fun callWebService() {
if (Utility.networkAvailable(app)) {
val retrofit = Retrofit.Builder().baseUrl(WEB_SERVICE_URL).addConverterFactory(MoshiConverterFactory.create()).build()
val service = retrofit.create(CourseService::class.java)
val serviceData = service.getCourseData(viewModel.pathName).body() ?: emptyList()
courseData.postValue(serviceData)
}
}
}
The purpose of the ViewModel here is because i am storing the Id of the selected RecyclerView item in order to send it to a server ViewModel 的目的是因为我存储了所选 RecyclerView 项目的 Id 以便将其发送到服务器
ViewModel instances are scoped to Fragments or Activities (or anything with a similar lifecycle), which is why you need to pass in a ViewModelStoreOwner
to the provider to get a ViewModel from it. ViewModel 实例的范围是片段或活动(或任何具有类似生命周期的东西),这就是为什么您需要将
ViewModelStoreOwner
传递给提供者以从中获取 ViewModel。 The point of ViewModels is that they will exist until the store they belong to is destroyed. ViewModel 的意义在于它们将一直存在,直到它们所属的商店被销毁。
The requireActivity
method doesn't work here, because you're not inside a Fragment. requireActivity
方法在这里不起作用,因为您不在 Fragment 中。
Some things to consider here:这里需要考虑的一些事情:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.