Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 374
Ravi Parmar Avatar asked Dec 23 '22 02:12

Ravi Parmar


1 Answers

Just for illustrating the answer with a quick example

final int TASK_COUNT = 4;
mProgressBar = findViewById(R.id.progressbar);
mProgressBar.setMax(TASK_COUNT);

// 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();

syncChain.getWorkInfosLiveData().observe(this, new Observer<List<WorkInfo>>() {
    @Override
    public void onChanged(List<WorkInfo> workInfos) {

        int finishedCount = 0;

        for (WorkInfo workInfo : workInfos) {
            if (workInfo.getState().isFinished() && workInfo.getState() == WorkInfo.State.SUCCEEDED) {
                finishedCount++;
            }
        }
        mProgressBar.setProgress(finishedCount);

        if (finishedCount == workInfos.size()) {
             mProgressBar.setEnabled(false);
        }
    }
});
like image 85
Zain Avatar answered Dec 26 '22 00:12

Zain