jwir3
jwir3

Reputation: 6209

How can I break out of a chain of RxJava calls?

I have the following set of RxJava operators:

  currentUser = mApi.getUserById(userToken, userId, userId)
                    .onErrorReturn(throwable -> null)
                    .map(userSet -> userSet.getUsers().get(0))
                    .doOnNext(user -> {
                        user.setToken(userToken);
                    })
                    .toBlocking()
                    .first();

The problem here is that the doOnNext() call and the map() call could be operating on null inputs. I could check within each of these calls for a null input, and act accordingly, but what I'd like to do is simply break the chain of operations and return a null value to currentUser.

Is this possible if I restructure my RxJava operations somehow?

Upvotes: 1

Views: 1915

Answers (1)

Malt
Malt

Reputation: 30305

Just move the onErrorReturn operator to the end of the chain, before toBlocking(). Then the exception caught at getUserById would propagate through the following operator's error handling (so the map and doOnNext won't be executed) until hitting the onErrorReturn and returning the null.

For example, this code prints null:

Integer myInt = Observable.<Integer> error(new RuntimeException())
            .doOnNext(item -> System.out.println("doOnNextInvoked"))
            .onErrorReturn(throwable -> null)
            .toBlocking().first();

System.out.println(myInt);

While this one:

Integer myInt = Observable.<Integer> error(new RuntimeException())
            .onErrorReturn(throwable -> null)
            .doOnNext(item -> System.out.println("doOnNextInvoked"))
            .toBlocking().first();

System.out.println(myInt);

prints

doOnNextInvoked
null

So we see that the doOnNext was invoked in the second case, but not the first.

Upvotes: 2

Related Questions