[英]Merge results from multiple API calls without using RxJava?
Referring to the answer here , just wondering, can we achieve the same without using RxJava?参考这里的答案,只是想知道,我们可以在不使用 RxJava 的情况下实现相同的功能吗? For example, using MediatorLiveData can combine multiple live data sources;
比如使用MediatorLiveData可以组合多个实时数据源; is there any way of getting results from multiple API calls, just by using androidx libraries?
有没有办法从多个 API 调用中获取结果,只需使用 androidx 库?
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):我认为是在不使用 RxJava 的情况下处理异步 Retrofit 请求(问题的核心是 Retrofit 响应的异步性),您有 3 个选择(也许我错过了一些东西):
suspend
to all your request-methods, then call them from inside the coroutine, and then to combine all results using collections' methods, for example.suspend
添加到所有请求方法中,然后从协程内部调用它们,然后使用集合的方法组合所有结果,例如。 To use coroutines you have to use Kotlin (at least in this network-part of the code) and to add additional coroutines-dependencies.CompletableFuture
as a result to all your request-methods, then use operator thenCombine()
to combine results.CompletableFuture
作为结果设置为所有请求方法,然后使用运算符thenCombine()
组合结果。 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.至于你提到的 LiveData,没有内置的方法可以让 Retrofit 的结果包装在 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.
问题是 Retrofit 的结果不是实时的(例如,在 Room 框架中它们是实时的,并且结果有 LiveData-wrapper),因为没有到 API 服务器的实时连接正在等待。 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.
我认为您可以为此获得一些适配器,然后使用 MediatorLiveData 但它不会是开箱即用的,无论如何您应该使用上述异步方法之一来处理 Retrofit 的响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.