Search code examples
androidandroid-livedataandroid-workmanager

How to Observe the live data in work manager with chain of works?


I have 3 tasks A,B, and C . I want to observe the live data for this chain and have a progress bar that shows the work in progress and once work its completed it should disable the progress bar.

    // One Time work for A class
         OneTimeWorkRequest Awork = new OneTimeWorkRequest
                          .Builder(A.class)
                          .setConstraints(Miscellaneous.networkConstraint())
                          .addTag("A")
                          .build();
            //same for B and C
            //work chain 
           WorkContinuation syncChain = WorkManager.getInstance()
                              .beginWith(Awork)
                              .then(Bwork)
                              .then(Cwork);

         syncChain.enqueue();

Solution

  • You can use the mWorkManager.getWorkInfosByTagLiveData(TAG_OUTPUT); method to recover the status of your WorkRequest as shown in the WorkManager codelab.

    This allows you to retrieve the status from the WorkRequest as a 'WorkInfo.State' enum with these possible states:

    • BLOCKED
    • CANCELLED
    • ENQUEUED
    • FAILED
    • RUNNING
    • SUCCEEDED

    However, I'm not sure that this gives you enough granularity to manage a progress bar.

    Retrieving the information as I wrote above gives you the flexibility to retrieve the WorkInfo for every WorkRequest.
    As an alternative you can retrieve a list of WorkInfo for the WorkContinuation:

    public abstract LiveData<List<WorkInfo>> getWorkInfosLiveData