我有这样的方法
public void loadData(String city) {
mWeatherDataSource.getWeatherData(city)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableSingleObserver<List<WeatherResponse>>() {
@Override
public void onSuccess(List<WeatherResponse> weatherResponses) {
}
@Override
public void onError(Throwable e) {
}
});
}
和
public Single<List<WeatherResponse>> getWeatherData(String city) {
return mApiService.getDataWeather(city, API_KEY);
}
这很好,但我希望loadData与String... city
(或List)参数一起使用,该参数多次运行getWeatherData
。
结果必须合并(例如):
@Override
public void onSuccess(List<WeatherResponse> weatherResponses) {
}
答案 0 :(得分:0)
您可以通过以下方式实现:
fromArray
运算符将String.. cities
数组中的每个城市发送到流中; flatMapSingle
运算符为发射的每个城市调用您的API flatMap
和fromIterable
获取检索到的WeatherResponse列表,并在流中一一发出toList
运算符将所有分组到一个列表中 public void loadData(String... cities) {
Observable.fromArray(cities)
.flatMapSingle((Function<String, SingleSource<List<WeatherResponse>>>) city -> getWeatherData(city))
.flatMap((Function<List<WeatherResponse>, ObservableSource<WeatherResponse>>) Observable::fromIterable)
.toList()
.subscribe(list -> {
// do whatever with your single list with all items
});
}