How to create custom tasks for Firebase using the Google Play services Task API

后端 未结 2 372
北恋
北恋 2021-01-13 01:12

I\'d like to create custom tasks like these ones in firebase in order to chain my API async calls. How can I achieve that?

相关标签:
2条回答
  • 2021-01-13 02:14

    Suppose you have a Document class, you could do as follow:

    Create successfuly resolved task

    Tasks.<Document>forResult(document);
    

    Create a failed task

    Tasks.forException(new RuntimeException("Cool message"));
    

    Create from Callable

    interface CreateDocument extends Callable<Document> {
        @Override
        Document call();
    }
    Tasks.call(new CreateDocument());
    

    Create using task completion source

    Task<Document> createDocument() {
        TaskCompletionSource<Document> tcs = new TaskCompletionSource();
        if (this.someThingGoesWrong()) {
            tcs.setException(new RuntimeException("Cooler message"));
        } else {
            tcs.setResult(Document.factory());
        }
    
        tcs.getTask();
    }
    
    0 讨论(0)
  • 2021-01-13 02:16

    There are a few ways to create a custom task using the Play services Task API.

    First, there is Tasks.call(Callable). The Callable you pass is scheduled for immediate execution on the main thread, and you get a Task in return, with a generic parameter of the return type of the Callable. This Task resolves successfully with that return value, or an error if the Callable throws an exception.

    The other method is Tasks.call(Executor, Callable), which is exactly like the other method, except the given callable is scheduled for immediate execution on a thread managed by the given Executor. It's up to you to find or create an Executor that's appropriate for your work.

    Lastly, there is also TaskCompletionSource, which lets you create a Task and manually resolve it to success or failure from the result of some other item of work not directly related to a Task.

    For more details, check out my blog series on Tasks. I cover these methods in part three and part four.

    0 讨论(0)
提交回复
热议问题