Search code examples
javaandroidkotlinkotlin-coroutinesandroid-workmanager

Android WorkManager getting reference to Worker class


I'm facing following problem: there's my class which inherits CoroutineWorker. Logic of this worker is complicated enough, in fact doWork() calls bunch of other routines inside and catches (collect) results of several StateFlows, like:

   override suspend fun doWork(): Result {
      //blah-blah
        withContext(Dispatchers.Default) {
            _scanResultState.collectLatest {
                //blah-blah
            }
        }
      return ...
   }

Questions:

  1. Can I somehow return/put collected StateFlow values (values are simple primitive objects) to Worker.Result?
  2. Or as an option - how could I listen/collect those StateFlow in other class - outside of my Worker?

Since, Worker class instantiated by WorkManager - I can't have a reference to concrete instance of Worker. E.g. in Service I could have reference to instance through bound Services, but in case of WorkManager looks like it's impossible.

Any ideas?


Solution

  • Well if you want to share a flow from your Worker class to your app, you can use room database for that, for example let's say that you want to share a Flow<List> from your Worker to achieve that you need to follow these steps:

    1. First create a Book Entity in your room database.
    2. Second add a function in your Dao that returns a Flow<List>.
    3. Third collect that flow in your app (view model, repository, fragment...).
    4. Finally in your Worker keep adding books to your room database.

    With these 4 steps you will be able to collect data from Worker in any other class.

    I hope that my answer was clear and helpful :D