Android
Android

Reputation: 279

Android. RxJava 2: Parallel multiple network calls

I need make two parallel requests with RxJava. For this I use zip operator. Here is my code:

  public Disposable getBooksAndAuthors(String id, ReuqestCallback requestCallback) {
        return singleRequest(Single.zip(
                getBooks(id).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()),
                getAuthors(id).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()),
                (book, author) -> new ZipResponseWrapper(book, author).getResponse()), requestCallback);
    }

private <T extends NetworkResponse> Disposable singleRequest(Single<T> single, RequestCallback requestCallback) {
    return single.doOnSubscribe(d -> requestCallback.onStartRequest())
            .doOnSuccess(s -> requestCallback.onSuccess(s))
            .doOnError(ErrorConsumer.consume((t) -> requestCallback.onError(t)))
            .doFinally(() -> requestCallback.onFinish())
            .subscribe();
}

But I don’t understand how to receive response separately for each request. That is, I need to, if the answer came to the first request, immediately display the data received from this request and not wait for a response to the second request. And after the answer to the second request arrives, display the data received on the second request.This is necessary due to the fact that the second request fulfills a long time. Please help me.

Upvotes: 1

Views: 1201

Answers (2)

ExpensiveBelly
ExpensiveBelly

Reputation: 454

My suggestion (in Kotlin though):

val id = 0L
    
Observables.combineLatest(
        getBooks(id).startWith(emptyList<Book>()).subscribeOn(Schedulers.io()).observeOn(Schedulers.computation()),
        getAuthor(id).startWith(emptyList<Author>()).subscribeOn(Schedulers.io()).observeOn(Schedulers.computation())
    ) { book: List<Book>, author: List<Author> ->
        Pair(book, author)
    }.skip(1)
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe { (books: List<Book>, authors: List<Author>) ->
            view.show(books)
            view.show(authors)
        }

Upvotes: 1

Kristy Welsh
Kristy Welsh

Reputation: 8340

Here is an example of how you can handle it with the responses for each function:

val disposable = Observable.zip(
    firstNetworkCall().subscribeOn(Schedulers.io()),
    secondNetworkCall().subscribeOn(Schedulers.io()),
    BiFunction{ 
      firstResonse: ResponseOneType, 
      secondResponse: ResponseTwoType -> 
      combineResult(firstResponse, secondResponse) }))
.observeOn(AndroidSchedulers.mainThread())
.subscribe { it -> doSomethingWithIndividualResponse(it) }

Upvotes: 1

Related Questions