0

这听起来像是一件基本的事情,但我不知道如何实现它。我有一个 Worker 类可以完成一些任务。

@NonNull
    @Override
    public Worker.Result doWork() {
        //Some work that involves liveData 
        return Worker.Result.SUCCESS;
    }

@Override
    public void onChanged(@Nullable String s) {    
        if(//Something){
            //If this happens only then should the Worker return success
        }else{
            //Else return Failure/Retry
        }
    }

我想根据我拥有的 liveData 返回的值返回成功。我不知道该怎么做。有人可以指导我。谢谢!!

4

1 回答 1

1

使用CountDownLatch可以解决Worker中异步调用的问题:

final WorkerResult[] result = {WorkerResult.RETRY};
CountDownLatch countDownLatch = new CountDownLatch(1);    

@NonNull
@Override
public Worker.Result doWork() {
    //Some work that involves liveData 
    try {
        countDownLatch.await(); // This will make our thread to wait for exact one time before count downs
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return result[0];
}

@Override
public void onChanged(@Nullable String s) {    
    if(//Something){
        //If this happens only then should the Worker return success
        result[0] = WorkerResult.SUCCESS;
    }else{
        //Else return Failure/Retry
        result[0] = WorkerResult.RETRY;
    }
    countDownLatch.countDown(); // This will count down our latch exactly one time & then our thread will continue
}

从这里结帐更多

于 2018-10-22T15:02:26.063 回答