Search code examples
androidandroid-workmanager

How to check PeriodicWorkRequest was completed?


Here's my observer (it's in the fragment)

workManager.getWorkInfoByIdLiveData(work.id)
            .observe(viewLifecycleOwner, { workInfo ->
                if (workInfo != null && workInfo.state == WorkInfo.State.ENQUEUED) {
                    //update UI
                }
            })

I need to update my UI on every PeriodicWorkRequest run. But it's state is always ENQUEUED according to documentation. getRunAttemptCount() gets reset between successful runs as well.

So, is there a way to check the completion of my work?

I thought it would be easier because in my Worker in doWork() I return Result.success() or Result.failure() and I even get a record about this in my terminal. Why I can't check for this in my code?


Solution

  • As per the documentation, a PeriodicWorkRequest can never transition to SUCCEEDED. As soon as a job is done, the next execution is put into the queue. Thus, the state is always pending between ENQUEUED and RUNNING.

    Here is a visualization from Pietro Maggi, one of Googles Developer Advocates. More easily digestable information on PeriodicWorkRequest can be found in his blog article: https://medium.com/androiddevelopers/workmanager-periodicity-ff35185ff006

    enter image description here