0

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

1 Answers1

0

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?
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • I am storing the ID of a selected RecyclerView item in the SharedViewModel class in order to send it through a http post request to filter my the SQL request on a server based on that selection –  Apr 29 '20 at 18:32
  • i suppose i don' need to use the ViewModel, but how to i pass the Id of a selected RecyclerView item to a http post? –  Apr 29 '20 at 18:33
  • Aren't you calling this repository from the ViewModel? Could you add this as a parameter to `callWebService`? – zsmb13 Apr 29 '20 at 18:38
  • i am not calling this respository from the view model –  Apr 29 '20 at 18:53
  • What i want to do simply is, put the ReyclerViewItem Id into the getCourseData() function –  Apr 29 '20 at 18:54
  • If i hardcode the value getCourseData("WEB001"), everything will work, the point is where do i store the retrieved Id of the selected RecyclerView Item in order to use it in the getCourseData() function? –  Apr 29 '20 at 18:56