简体   繁体   中英

Merge results from multiple API calls without using RxJava?

Referring to the answer here , just wondering, can we achieve the same without using RxJava? For example, using MediatorLiveData can combine multiple live data sources; is there any way of getting results from multiple API calls, just by using androidx libraries?

What I think is to handle asynchronous Retrofit requests (the core of the question is asynchrony of Retrofit's response) without using RxJava you have 3 choices (maybe I miss something):

  1. Plain callbacks . I guess this way doesn't need comments.
  2. Kotlin coroutines . For that you need to add suspend to all your request-methods, then call them from inside the coroutine, and then to combine all results using collections' methods, for example. To use coroutines you have to use Kotlin (at least in this network-part of the code) and to add additional coroutines-dependencies.
  3. Java8's CompletableFuture . For that you need to set CompletableFuture as a result to all your request-methods, then use operator thenCombine() to combine results. To use Java8's features in Android you have to make some additional steps ( piece of documentation ).

As for LiveData you've mentioned there is no built-in way how to get Retrofit's result wrapped in LiveData. The thing is Retrofit's results are not live (for example in Room framework they are and there is LiveData-wrapper for result), since there is no live connection to API Server awaiting. I think you can get some adapter for that and then use MediatorLiveData but it wouldn't be out-of-the box and you should anyway use one of the mentioned asynchronous ways to handle Retrofit's response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM