如何忽略错误并继续无限流? [英] How to ignore error and continue infinite stream?
问题描述
我想知道如何忽略异常并继续无限流(在我的情况下是位置流)?
I would like to know how to ignore exceptions and continue infinite stream (in my case stream of locations)?
我正在获取当前用户位置(使用 Android-ReactiveLocation ),然后将其发送到我的API(使用 Retrofit ).
I'm fetching current user position (using Android-ReactiveLocation) and then sending them to my API (using Retrofit).
在我的情况下,当在网络调用过程中发生异常(例如超时)时,将调用onError
方法,流将自行停止.如何避免呢?
In my case, when exception occurs during network call (e.g. timeout) onError
method is invoked and stream stops itself. How to avoid it?
活动:
private RestService mRestService;
private Subscription mSubscription;
private LocationRequest mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(100);
...
private void start() {
mRestService = ...;
ReactiveLocationProvider reactiveLocationProvider = new ReactiveLocationProvider(this);
mSubscription = reactiveLocationProvider.getUpdatedLocation(mLocationRequest)
.buffer(50)
.flatMap(locations -> mRestService.postLocations(locations)) // can throw exception
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
}
RestService:
RestService:
public interface RestService {
@POST("/.../")
Observable<Response> postLocations(@Body List<Location> locations);
}
推荐答案
mRestService.postLocations(locations)
发出一项,然后完成.
如果发生错误,则会发出错误,从而完成流.
mRestService.postLocations(locations)
emit one item, then complete.
If an error occur, then it emit the error, which complete the stream.
在flatMap
中调用此方法时,错误继续出现在主"流上,然后流停止.
As you call this method in a flatMap
, the error continue to your "main" stream, and then your stream stops.
您所能做的就是将您的错误转换为另一个项目(如此处所述: https://stackoverflow.com/a/28971140/476690 ),但不在您的主流(如我想您已经尝试过)上,而是在mRestService.postLocations(locations)
上.
What you can do is to transform your error into another item (as described here : https://stackoverflow.com/a/28971140/476690 ), but not on your main stream (as I presume you already tried) but on the mRestService.postLocations(locations)
.
这样,此调用将发出一个错误,该错误将转换为一个项/另一个可观察的项,然后完成. (不调用onError
).
This way, this call will emit an error, that will be transformed to an item/another observable and then complete. (without calling onError
).
在消费者视图中,mRestService.postLocations(locations)
将发出一项,然后完成,就像一切都成功了.
On a consumer view, mRestService.postLocations(locations)
will emit one item, then complete, like if everything succeed.
mSubscription = reactiveLocationProvider.getUpdatedLocation(mLocationRequest)
.buffer(50)
.flatMap(locations -> mRestService.postLocations(locations).onErrorReturn((e) -> Collections.emptyList()) // can't throw exception
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
这篇关于如何忽略错误并继续无限流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!