How to pass data from failed child worker to last worker in chain with android CoroutineWorkers

Viewed 153

My current android application employs chained workers to perform complex background tasks.

Im observing only the last worker in the chain to detect whether or not the complete chain has completed successfully. This approach has been acceptable till now, as I have a new requirement where I need to also pass data when a worker fails.

is my only option to start observing all workers in the chain?

or

is it possible to set output data in a failing child worker and access it from the workinfo obtained from observing the last worker in the chain?

for example if i have a chain of 5 sequential workers as follows:-

WorkerA
WorkerB
WorkerC
WorkerD
WorkerZ

I am only observing WorkerZ, and WorkerC fails and sets outputData in its result, is there any way I can access that WorkData from observing only WorkerZ?

1 Answers

There is no need to observe all the workers. If you are returning data with Result.failure in each worker, you can easily find which worker failed and what was its output data like this:

 WorkManager.getInstance(context)
        .getWorkInfosForUniqueWorkLiveData(UNIQUE_WORK_NAME)
        .observeForever { workInfos ->
            if(it.state == WorkInfo.State.FAILED){ //failed worker
                  val failureResult = it.outputData
            }
        }

or like this:

val failureResult = WorkManager.getInstance(context)
        .getWorkInfosForUniqueWork(UNIQUE_WORK_NAME)
        .get()
        .firstOrNull{
            it.state == WorkInfo.State.FAILED
        }
        ?.outputData
Related