user2908751
user2908751

Reputation: 195

Send multiple requests using RxJava

I am very new to using RxJava with Retrofit in Android. I have successfully written the API calls and developed the interface too. Now, I want to write my code in a way that I can send two requests: second request depending upon the values of first request. Can someone guide me if this is possible? If so then how? Any code snippet will really be helpful.

For example: following are two requests:

mCompositeDisposable.add(fcService.getStationList()
                .subscribeOn(Schedulers.io()) // "work" on io thread
                .observeOn(AndroidSchedulers.mainThread()) // "listen" on UIThread
                .subscribe(this::handleResults, this::handleError)
        );


mCompositeDisposable.add(fcService.getStationSensor("12345678")
                    .subscribeOn(Schedulers.io()) // "work" on io thread
                    .observeOn(AndroidSchedulers.mainThread()) // "listen" on UIThread
                    .subscribe(this::handleResults, this::handleError)
            );

Second request is possible with the value from the first request's response. Is it possible to merge these two requests in a way that I write code only once for them?

Upvotes: 0

Views: 696

Answers (1)

Jesús Barrera
Jesús Barrera

Reputation: 459

With the flatMap operator you can check the response of the first call and choose the next action to follow, in this way you build a new Observable that you can subscribe to (The next "code" is kotlin style):

Single<StationSensor> newSingle = 
fcService.getStationList().flatMap{ stationList ->
    when(stationList){
        "OK_value" -> fcService.getStationSensor(stationList)
        else -> Single.error(RuntimeException("Error response"))
    }
}

Upvotes: 1

Related Questions