How to continue streaming items after error in RxJava?

送分小仙女□ 提交于 2019-12-06 15:03:46

the trick is to wrap the value, which would be transformed somehow, into a new observable and flatmap over it as in the following example. Each value in the flatMap can now throw a exception and handle it value by value. Becuase the substream in flatMap consists only of one element, it does not matter if the observable will be closed after onError. I use RxJava2 as test-environment.

@Test
public void name() throws Exception {
    Observable<String> stringObservable = Observable.fromArray("1", "2", "3")
            .flatMap(x -> {
                return Observable.defer(() -> {
                    try {
                        if (x.equals("2")) {
                            throw new NullPointerException();
                        }
                        return Observable.just(x + "-");
                    } catch (Exception ex) {
                        return Observable.error(ex);
                    }
                }).map(s -> {
                    if (s.equals("3-")) {
                        throw new IllegalArgumentException();
                    }
                    return s + s;
                }).take(1)
                        .zipWith(Observable.just("X"), (s, s2) -> s + s2)
                        .onErrorResumeNext(Observable.empty());
            });

    TestObserver<String> test = stringObservable.test();

    test.assertResult("1-1-X");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!