让TaskCompletionSource工作(Firestore的Android任务)

问题描述 投票:0回答:1

在这些其他stackoverflow问题的答案中:https://stackoverflow.com/a/41360829/1932522https://stackoverflow.com/a/40557237/1932522提供了一些示例,展示了如何利用TaskCompletionSource在任务中运行延迟调用。

当在一个简单的例子(下面提供)中实现它时,我遇到了.continueWith( new TaskerB() ));行不会编译的问题,因为编译器期望一个Task作为第一个参数:Incompatible equality constraint: Task<String> and String,我希望这个参数应该只是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() ));
    }
java android firebase google-play-services
1个回答
2
投票

使用continueWithTask代替:

Tasks.call(new StartTask())
        .continueWithTask(new TaskerA())
        .continueWith(new TaskerB());
© www.soinside.com 2019 - 2024. All rights reserved.