Search code examples
androidandroid-architecture-componentsandroid-viewmodelandroid-workmanager

How to get a ViewModel from a Worker class?


  1. I have an Activivity in my application called MainActivity.
  2. The MainActivity is associated with a ViewModel in the OnCreate method

    ...
    val someViewModel = ViewModelProviders.of(this).get(SomeViewModel::class.java)
    ...
    
  3. I do some background work with Workers.

    val someWork = OneTimeWorkRequestBuilder<LoginWorker>().build() WorkManager.getInstance().beginUniqueWork("SOMEWORK", ExistingWorkPolicy.REPLACE, captivePortalWork).enqueue()

  4. Here comes the issue... The worker for example do a loop 10 times and in each time just sleep for a second... so we have a 10 seconds background work. I want to update the ViewModel to show the progress of the background work and uptade the UI each time.

    A) I can acces to the View model from the MainActivity and observe the worker but and I can only update the ViewModel when the progress are Succeded or Failed... that means I can show a progress when the work is 0 or 100% done.

    B) If I could access the ViewModel from the Worker class, I could update the ViewModel at any time. But I don't know how... this method doesn't work inside a Worker class.

    val someWork = ViewModelProviders.of(this).get(SomeViewModel::class.java)

    How can I get a ViewModel from a Worker class?


Solution

  • You cannot use a ViewModel for this. You need to use your own Room Database and expose a LiveData to your UI to show progress.