[英]Continue subscribing for data even after exception using rx notifications
[英]Continue subscribing for data even after error from Observable - rxjava
我是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();
}
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();
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.