WorkManager observing state with Livedata

1.7k views Asked by At

I'm using OneTimeWorkRequest to do some work and observing its status with getWorkInfosByTagLiveData(), after application is killed and/or activity is recreated and observer is created again in onCreate(),i'm receiving recently done work infos and toast message is triggered, i think WorkManager somehow caches recently done workInfos. I want to only show toast when work is currently running with state changes and not after activity recreation.

viewModel

public class MainViewModel extends ViewModel {
    private static final String POST_WORKER_TAG = "WorkerTag";
    private LiveData<List<WorkInfo>> workInfo;

    @ViewModelInject
    public MainViewModel(WorkManager workManager) {
        this.workManager = workManager;
        this.workInfo = workManager.getWorkInfosByTagLiveData(POST_WORKER_TAG);
    }

    public LiveData<List<WorkInfo>> getWorkInfo() {
        return workInfo;
    }

    public void startPostWorker() {
        OneTimeWorkRequest postRequestWorker = new OneTimeWorkRequest.Builder(PostRequestWorker.class)
                .addTag(POST_WORKER_TAG)
                .build();
        workManager.enqueue(postRequestWorker);
    }


in activity onCreate()

MainViewModel mainViewModel = new ViewModelProvider(this).get(MainViewModel.class);

mainViewModel.getWorkInfo().observe(this, workInfos -> {
            if (workInfos != null && !workInfos.isEmpty()) {
                WorkInfo workInfo = workInfos.get(workInfos.size() - 1);
                if (workInfo.getState() == WorkInfo.State.ENQUEUED) {
                   Toast.makeText(context, "ENQUEUED", Toast.LENGTH_SHORT).show();
                } else if (workInfo.getState() == WorkInfo.State.SUCCEEDED) {
                   Toast.makeText(context, "SUCCEEDED", Toast.LENGTH_SHORT).show();
                } else if (workInfo.getState() == WorkInfo.State.FAILED) {
                   Toast.makeText(context, "FAILED", Toast.LENGTH_SHORT).show();
                }
            }
        });
1

There are 1 answers

0
H. Ekici On

LiveData re-publishes data when new observer registered, to avoid that you can set a boolean after publishing updates or implement it with Rx, SingleLiveData or Kotlin Flow