How to make two Retrofit calls in jail with RxJava?

3

I make a call to retrieve some data and the second call - which should be done within the first - uses one of the fields of 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 first call fields to do the second? I'm using Kotlin and working with RxJava.

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

    
asked by anonymous 12.12.2017 / 00:12

1 answer

1

I believe that in your case it is better to do it inside the chain , and not in the 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 something else):

restApi.searchDoc("language", "title_query")
    .flatMap({ restApi.doSomethingWithDoc(it.field) }, { doc, smt -> Pair(doc, smt) }, false)
    .subscribe { pair ->
    }
    
13.12.2017 / 20:17