1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I just googled both coroutines and CompletableFuture and both seem very interesting. At a first glance coroutines seems easier to understand and the code looks cleaner. I will try with coroutines first. Personally, which one would you suggest? Most of my code is already in Kotlin and I'm already using Java 8
I think in most projects you'll meet RxJava or coroutines for handling asynchronous work, in some projects I've met custom adapter for LiveData. Decision is opinionated. General trend in Kotlin to use coroutines, but it's not golden rule. Personally I would use coroutines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.