How to make two Retrofit calls in chain with RxJava?



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

    Question summarized: How do I use the recovered data in the first call to make the second one inside the RxAndroid?



  • I believe that in your case it is better to do within chain, not subscribe. Use the operator http://reactivex.io/documentation/operators/flatmap.html :

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




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2