How to make two Retrofit calls in chain with RxJava?

Question:

I make a call to retrieve some data and the second call – which should be done inside the first – uses one of the fields from the previous call.

val restApi = retrofit.create(RestAPI::class.java)
testAPI.searchDoc("language", "title_query")
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe { p0 ->
             /** É aqui onde eu quero recuperar os dados de p0 e com eles fazer 
                 a segunda chamada. **/
            }
        }

How do I use one of the fields from the first call to make the second one? I'm using Kotlin and working with RxJava.

Short question: How do I use the data retrieved in the first call to make the second one inside RxAndroid?

Answer:

I believe that in your case it is better to do within the chain , and not subscribe. Use the flatMap operator:

val restApi = retrofit.create(RestAPI::class.java)
restApi.searchDoc("language", "title_query")
    .flatMap { restApi.doSomethingWithDoc(it.field) }
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe { p0 ->

    }

If you need the original value, you can use the mapper function and return a Pair (or anything else):

restApi.searchDoc("language", "title_query")
    .flatMap({ restApi.doSomethingWithDoc(it.field) }, { doc, smt -> Pair(doc, smt) }, false)
    .subscribe { pair ->
    }
Scroll to Top