'WorkManager - How to get OutputData from a periodic work

I'm using a PeriodicWorkRequest for getting some data from the internet every hour. I would like to update the UI of my app with the Result returned by the worker. This is the code I have now:

workManager.enqueueUniquePeriodicWork("name", ExistingPeriodicWorkPolicy.REPLACE, work)

workManager
  .getWorkInfoByIdLiveData(work.id)
  .observe(this, { workInfo ->
     if (workInfo?.state == WorkInfo.State.SUCCEEDED) {
        // it never arrives here for updating the UI
     }
  }

Given the life cycle of a periodic work, the state SUCCEEDED is never reached, as it bounces between RUNNING and ENQUEUED; in these two states the Result.OutputData object is empty, so I cannot use it.

The app is thought not to be kept open all the time, but when it's opened it should show the last data retrieved from the worker.

How can I retrieve the OutputData of the Result returned by the doWork() function? Is a periodic work the right tool for my use case?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source