我是rx java的新手,在下面的代码中,只要有异常,订阅者就会停止订阅数据。在这种情况下" hello3"永远不会打印。 如何让订户继续接收数据?
public class ReactiveDataService
{
public Observable<String> getStreamData()
{
return Observable.create(o -> {
o.onNext("hello1");
o.onNext("hello2");
o.onError(new TimeoutException("Timed Out!"));
o.onNext("hello3");
});
}
}
Observable<String> watcher = new ReactiveResource().getData()
.timeout(3, TimeUnit.SECONDS)
.onErrorResumeNext(th -> {
return Observable.just("timeout exception");
});
watcher.subscribe(
ReactiveResource::callBack,
ReactiveResource::errorCallBack,
ReactiveResource::completeCallBack
);
public static Action1 callBack(String data)
{
System.out.println("--" + data);
return null;
}
public static void errorCallBack(Throwable throwable)
{
System.out.println(throwable);
}
public static void completeCallBack()
{
System.out.println("On completed successfully");
}
private Observable<String> getData()
{
return new ReactiveDataService().getStreamData();
}
答案 0 :(得分:1)
RxJava最多只允许一个onError
,这意味着流程的结束。如果您发现自己想要发出更多错误,可能与正常项目交错,则意味着您需要一个可以代表两者的数据类型,配对或记录类。 io.reactivex.Notification
是一种选择。
public Observable<Notification<String>> getStreamData() {
return Observable.create(o -> {
o.onNext (Notification.createOnNext("hello1"));
o.onNext (Notification.createOnNext("hello2"));
o.onError(Notification.createOnError(new TimeoutException("Timed Out!")));
o.onNext (Notification.createOnNext("hello3"));
o.onComplete();
});
}