Unique OneTimeWorkRequest in Workmanager

前端 未结 4 1573
[愿得一人]
[愿得一人] 2020-12-31 09:07

We are using OneTimeWorkRequest to start background task in our project.

  1. At application start, we are starting the OneTimeWorkRequest (say req A)
  2. De
4条回答
  •  太阳男子
    2020-12-31 09:19

    Using getStatusesByTag returns LiveData of List it was made as LiveData because WorkStatus is kept in Room DB and WorkManger has to query it first on background thread then deliver the result. so you must observe to get the real value when it's available . calling getValue() will return last value of the LiveData which isn't available on the time you call it.

    What you can do

    public static LiveData isMyWorkerRunning(String tag) {
        MediatorLiveData result = new MediatorLiveData<>();
        LiveData> statusesByTag = WorkManager.getInstance().getStatusesByTag(tag);
        result.addSource(statusesByTag, (workStatuses) -> {
            boolean isWorking;
            if (workStatuses == null || workStatuses.isEmpty())
                isWorking = false;
            else {
                State workState = workStatuses.get(0).getState();
                isWorking = !workState.isFinished();
            }
            result.setValue(isWorking);
            //remove source so you don't get further updates of the status
            result.removeSource(statusesByTag);
        });
        return result;
    }
    

    Now you don't start the task until you observe on the returning value of isMyWorkerRunning if it's true then it's safe to start it if not this mean that another task with the same tag is running

提交回复
热议问题