如何使用 RxJava 逐个读取 String 数组成员并为第一个结果调用网络 API?
How to read a String array members one by one using RxJava and call a network API for the first result?
我有一个字符串数组,例如:
cities = new String[]{"a", "b", "c", "Berlin", "e"}
我想调用我的天气 api 一个一个地使用它的成员作为参数,并取第一个没有异常且有天气结果的结果(换句话说,它是一个城市的名称!).
我已经试过了,但是它在第一个异常处停止并且不会继续处理其他数组成员!
Observable.from(cities)
.flatMap(interactor::loadWeather)
.filter(weatherCurrent -> weatherCurrent != null)
.first()
.observeOn(scheduler.mainThread())
.subscribe(...
第一个结果优先,我想退出使用其他成员调用。
According to the sample String array the api should call with a
as city param and return nothing, call with b
as city and return nothing, but as Berlin
it would return the weather info, and do not call using e
.
有什么想法吗?
使用onErrorResumeNext
和concatMap
:
Observable.from(cities)
.concatMap(city -> interactor
.loadWeather(city)
.onErrorResumeNext(Observable.empty()))
.filter(weatherCurrent -> weatherCurrent != null)
.first()
.observeOn(scheduler.mainThread())
.subscribe(...
我有一个字符串数组,例如:
cities = new String[]{"a", "b", "c", "Berlin", "e"}
我想调用我的天气 api 一个一个地使用它的成员作为参数,并取第一个没有异常且有天气结果的结果(换句话说,它是一个城市的名称!).
我已经试过了,但是它在第一个异常处停止并且不会继续处理其他数组成员!
Observable.from(cities)
.flatMap(interactor::loadWeather)
.filter(weatherCurrent -> weatherCurrent != null)
.first()
.observeOn(scheduler.mainThread())
.subscribe(...
第一个结果优先,我想退出使用其他成员调用。
According to the sample String array the api should call with
a
as city param and return nothing, call withb
as city and return nothing, but asBerlin
it would return the weather info, and do not call usinge
.
有什么想法吗?
使用onErrorResumeNext
和concatMap
:
Observable.from(cities)
.concatMap(city -> interactor
.loadWeather(city)
.onErrorResumeNext(Observable.empty()))
.filter(weatherCurrent -> weatherCurrent != null)
.first()
.observeOn(scheduler.mainThread())
.subscribe(...