Work States and observing work

Work States

As your work goes through its lifetime, it goes through various States. Later in this document, we will talk about how to observe the changes. But first, you should learn about each of them:

  • Work is in the BLOCKED State if it has prerequisite work that hasn't finished yet.
  • Work that is eligible to run as soon as its Constraints and timing are met is considered to be ENQUEUED.
  • When a worker is actively being executed, it is in the RUNNING State.
  • A worker that has returned Result.success() is considered to be SUCCEEDED. This is a terminal State; only OneTimeWorkRequests may enter this State.
  • Conversely, a worker that returned Result.failure() is considered to be FAILED. This is also a terminal State; only OneTimeWorkRequests may enter this State. All dependent work will also be marked as FAILED and will not run.
  • When you explicitly cancel a WorkRequest that hasn't already terminated, it enters the CANCELLED State. All dependent work will also be marked as CANCELLED and will not run.

Observing your work

After you enqueue your work, WorkManager allows you to check on its status. This information is available in a WorkInfo object, which includes the id of the work, its tags, its current State, and any output data.

You can obtain WorkInfo in one of three ways:

The LiveData variants of each of the methods allow you to observe changes to the WorkInfo by registering a listener. For example, if you wanted to display a message to the user when some work finishes successfully, you could set it up as follows:

Kotlin

WorkManager.getInstance(myContext).getWorkInfoByIdLiveData(uploadWorkRequest.id)
        .observe(lifecycleOwner, Observer { workInfo ->
            if (workInfo != null && workInfo.state == WorkInfo.State.SUCCEEDED) {
                displayMessage("Work finished!")
            }
        })

Java

WorkManager.getInstance(myContext).getWorkInfoByIdLiveData(uploadWorkRequest.getId())
        .observe(lifecycleOwner, new Observer<WorkInfo>() {
            @Override
            public void onChanged(@Nullable WorkInfo workInfo) {
              if (workInfo != null && workInfo.state == WorkInfo.State.SUCCEEDED) {
                  displayMessage("Work finished!")
              }
            }
        });