How to make two Retrofit chain calls with Rxjava?

Asked

Viewed 121 times

3

I make a call to recover some data and the second call - which should be made inside the first one - 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. **/
            }
        }

As I use one of the fields of the first call to make the second? I am using Kotlin and working with Rxjava.

Short question: How I use the recovered data in the first call to make the second one within Rxandroid?

1 answer

1

I believe in your case it’s best to do inside the chain, not subscribe. Use the operator flatMap:

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 mapping 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 ->
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.