让 TaskCompletionSource 正常工作(Android 个 Firestore 任务)

Getting TaskCompletionSource working (Android tasks for Firestore)

在这些对其他 Whosebug 问题的回答中: and 提供的示例展示了如何使用 TaskCompletionSource 能够 运行 在任务中延迟调用。

在一个简单的示例(如下提供)中实现它时,我 运行 遇到了 .continueWith( new TaskerB() )); 行无法编译的问题,因为编译器需要一个 Task 作为第一个参数:Incompatible equality constraint: Task<String> and String,我希望这个参数应该只是String类型?谁可以帮助让这段代码工作并向我解释如何成功地使用 make use a 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() ));
    }

改用continueWithTask

Tasks.call(new StartTask())
        .continueWithTask(new TaskerA())
        .continueWith(new TaskerB());