java获取TaskCompletionSource工作(Firestore的Android任务)
在对其他stackoverflow问题的回答中:https://stackoverflow.com/a/41360829/1932522和https://stackoverflow.com/a/40557237/1932522提供了一些示例,说明如何利用TaskCompletionSource
在任务中运行延迟调用
在一个简单的示例(如下所示)中实现这一点时,我遇到了一个问题,即行.continueWith( new TaskerB() ));
将不会编译,因为编译器需要一个任务作为第一个参数:Incompatible equality constraint: Task<String> and String
,我希望这个参数应该是字符串类型?谁能帮助我使这段代码正常工作,并向我解释如何成功地使用TaskCompletionSource
注意:这个例子非常简单,在实际使用中,我会运行一个Firestore操作,设置一个监听器并从监听器内部调用tcs.setResult(..)
public class StartTask implements Callable<Integer>{
@Override
public Integer call() throws Exception {
return 1;
}
}
public class TaskerA implements Continuation< Integer, Task<String>>{
@Override
public Task<String> then(@NonNull Task<Integer> task) throws Exception {
final TaskCompletionSource<String> tcs = new TaskCompletionSource<>();
tcs.setResult( "value: " + task.getResult() );
return tcs.getTask();
}
}
public class TaskerB implements Continuation< String, Void>{
@Override
public Void then(@NonNull Task<String> task) throws Exception {
Log.d(TAG, "Output is: " + task.getResult());
return null;
};
}
public void runExample(){
Tasks.call( new StartTask() )
.continueWith( new TaskerA() )
.continueWith( new TaskerB() ));
}
# 1 楼答案
改用^{} :