Search code examples
androidretrofitretrofit2rx-javarx-android

RxJava Retrofit2 api multiple calls using subscribe or flatmap


I am making an API call using Retrofit2 and RxJava. The thing is that I want to make a second API call with the response (in this case an integer) received from the first api call. My doubt regards that both

Disposable subscribe(@NonNull Consumer<? super T> onSuccess, @NonNull Consumer<? super Throwable> onError) method and

    <R> Single<R> flatMap(@NonNull Function<? super T, ? extends SingleSource<? extends R>> mapper

look like are able to use the result of the first api call to call a second api call with it. So, which method, either subscribe or flatMap should I use to make a second api call with the result of the first and why? Do I have to use one or the other depending on whether the first api call's result is iterable or not?


Solution

  • I think you want something like this:

    fun firstRequest(): Single<Int> = Single.just(10)
    
    fun secondRequest(valueFromFirst: Int): Single<Int> = Single.just(valueFromFirst*2)
    
    fun mappedRequest(): Single<Int> {
      return firstRequest().flatMap {
        secondRequest(it)
      }
    }
    

    So, now you can have the mappedRequest() accessible from everywhere. You can "prepare" your request by doing:

    val requestSingle = mappedRequest()

    In this case, you have only the single. The request is not running yet, but is ready to run. To effectively run it:

    requestSingle.subscribe { handleResult(it) }