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();
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);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With