基于 liveData 事件成功实施 Worker
Implementing a Worker with success on the basis of liveData events
这听起来很基本,但我不知道如何实现。我有一个 Worker class 做一些任务。
@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
}
}
我想 return 根据我拥有的 liveData 所提供的值 return 取得成功。我不知道该怎么做。有人可以指导我。谢谢!!
使用 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
}
从 here
查看更多
这听起来很基本,但我不知道如何实现。我有一个 Worker class 做一些任务。
@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
}
}
我想 return 根据我拥有的 liveData 所提供的值 return 取得成功。我不知道该怎么做。有人可以指导我。谢谢!!
使用 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
}
从 here
查看更多