Raffu Raffu - 1 month ago 8
Android Question

RxJava + Retrofit : distinguish each request in multiple request call API

I have a list of city and I'd like to find the weather in each city.
e.g my list is cities = {london, berlin, headington}
so, my code is call api service for each city.

in my activity, this is how I request the weather each city :

for(String element : cities) {
presenter.getApi(element);
}


and in the presenter, which is implement the observer, this is the code to respond the result :

@Override
public void onNext (ResultObject result) {
// getName() function return city name
log.d("Result", result.getMain().getName() + result.getWeather().getDescription();
}


because this function (onNext) not come respectively as the request (we request london first then berlin then headington), so I don't know how to distinguish my london weather request with the berlin.

Also, in the API respond, its not always attached the request city. If I request Headington, the respond is Oxford.

Api service using Get, the link below (return an observable)
http://api.openweathermap.org/data/2.5/weather?q=headington&appid=90faa1669716319e787ca1ab5da48cbc

Answer

You can use a flatMap operator and make getApi return an observable to allow you to have the report and city in the same level.

Here an example

@Test
public void flatMapCities(){
    List<String> cities = Arrays.asList("London", "Berlin", "Moscow");
    Observable.from(cities)
            .flatMap(city -> getReport(city)
            .doOnNext(report->checkReport(city, report)));
}

private void checkReport(String city, String report) {
    //TODO:Check here the report and city
}

private Observable<String> getReport(String city) {
    return Observable.just("report");
}

You can see more examples here https://github.com/politrons/reactive