Search code examples
rx-javarx-java2reactivex

How to resume mapping a list if one fails RxJava


Given the following code, the onErrorResumeNext method will just replace an errored item in the list with "hi". How would I go about getting it to continue on with iterating through the rest of the list?

List<Object> list = new ArrayList<>();
list.add("one");
list.add(new Testo());
list.add("two");
list.add("three");    

Observable.fromIterable(list)
    .map(item -> item.toString())
    .onErrorResumeNext(Observable.just("hi"))
    .subscribe(item -> System.out.println(item), onError -> System.out.println("error"));

private static class Testo {
    @Override
    public String toString() {
        throw new NullPointerException();
    }
}

Solution

  • You can add an inner reactive stream, so the outer won't be terminated when error occures:

    Observable.fromIterable(list)
        .flatMap((item) -> Observable.just(item)
            .map(_item -> _item.toString())
            .onErrorResumeNext(Observable.just("hi")))
        .subscribe(item -> System.out.println(item), onError -> System.out.println("error"));