简体   繁体   中英

Continue subscribing for data even after error from Observable - rxjava

I'm new to rx java and in the below code whenever there is a exception the subscriber stop's subscribing the data. In this case "hello3" is never printed. How can I make the subscriber to continue receiving data?

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 only allows at most one onError which means the end of the flow. If you find yourself wanting to emit more errors, possibly interleaved with normal items, it means you need a data type, a pair or record class, that can represent both. The io.reactivex.Notification is one option.

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();
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM