【问题标题】:RxJava + Retrofit : distinguish each request in multiple request call APIRxJava + Retrofit:在多个请求调用API中区分每个请求
【发布时间】:2016-11-03 18:02:42
【问题描述】:

我有一个城市列表,我想查找每个城市的天气。 例如,我的列表是城市 = {伦敦、柏林、海丁顿} 所以,我的代码是为每个城市调用 api 服务。

在我的活动中,这就是我请求每个城市的天气的方式:

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

在实现观察者的演示者中,这是响应结果的代码:

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

因为这个函数(onNext)不是分别作为请求来的(我们先请求伦敦,然后是柏林,然后是headington),所以我不知道如何区分我的伦敦天气请求和柏林。

另外,在 API 响应中,它并不总是附加请求城市。如果我请求海丁顿,响应是牛津。

使用Get的Api服务,链接如下(返回一个observable) http://api.openweathermap.org/data/2.5/weather?q=headington&appid=90faa1669716319e787ca1ab5da48cbc

【问题讨论】:

  • 我希望有一些 RxJava 运算符为每个请求添加 uniq 参数。

标签: android rx-java retrofit2


【解决方案1】:

您可以使用 flatMap 运算符并让 getApi 返回一个 observable 以允许您将报告和城市置于同一级别。

这里是一个例子

@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");
}

您可以在此处查看更多示例https://github.com/politrons/reactive

【讨论】:

    猜你喜欢
    • 2021-09-04
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 2021-11-25
    • 2015-06-26
    • 2018-05-31
    • 2016-07-31
    • 2015-07-26
    相关资源
    最近更新 更多