简体   繁体   中英

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.

It is requiring "ViewModelStoreOwner" to be passed.

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 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. The point of ViewModels is that they will exist until the store they belong to is destroyed.

The requireActivity method doesn't work here, because you're not inside a Fragment.

Some things to consider here:

  • Do you really need ViewModel in this use case? Could you perhaps use just a regular class that you can create by calling its constructor?
  • Could you call this Repository from your ViewModel, and pass in any parameters you need from there?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM