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

后端 未结 2 393
北恋
北恋 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.forResult(document);
    

    Create a failed task

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

    Create from Callable

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

    Create using task completion source

    Task createDocument() {
        TaskCompletionSource tcs = new TaskCompletionSource();
        if (this.someThingGoesWrong()) {
            tcs.setException(new RuntimeException("Cooler message"));
        } else {
            tcs.setResult(Document.factory());
        }
    
        tcs.getTask();
    }
    

提交回复
热议问题