Search code examples
error-handlingrx-java2

RxJava how to handle Error without Quit flow


My scenario is like this: During a flow ,if there is an error happened during an element processing (in this example element is "three"), I still want keep processing the others.

In this example: I want to print "1,2,4,5" however, it just print "1 ,2".

   Observable<String> numbers = Observable.just("1", "2", "three", "4", "5");
    numbers.map(v->{
                return  Integer.parseInt(v);
            }).onErrorResumeNext(error->{return Observable.just(-1);})
            .filter(v-> {
                System.out.println("filter value smaller than 0");
                return  v>0;
            })
            .subscribe(s -> {

                System.out.println(s);
            });
}

I checked doc, "onErrorResumeNext" will instead relinquish control to the Observable returned from resumeFunction.

Is there way to print "1,2,4,5"?


Solution

  • The flow stops because there is a crash in map. The only way to avoid the flow being stopped is to not let map crash in your example. Put the parseInt into a try-catch and return -1 from the catch part.

    Observable<String> numbers = Observable.just("1", "2", "three", "4", "5");
    
    numbers.map(v -> {
        try {
            return Integer.parseInt(v);
        } catch (NumberFormatException ex) { // <--------------------------------------
            return -1;
        }
    })
    .filter(v -> {
        System.out.println("filter value smaller than 0");
        return  v > 0;
    })
    .subscribe(s -> {
        System.out.println(s);
    });