DEV Community

Cover image for Matt's Tidbits #40 - RxJava doOnSubscribe() behavior explained
Matthew Groves
Matthew Groves

Posted on • Originally published at Medium

Matt's Tidbits #40 - RxJava doOnSubscribe() behavior explained

Last time I wrote about why writing tests is so important. This week, I wanted to discuss a behavior of RxJava’s doOnSubscribe() that I recently discovered.

I’ve been working with RxJava a lot lately, and encountered a case where an error was being thrown in a doOnSubscribe() block, and I wasn’t sure if/how that might impact the rest of the Rx chain.

Here’s the code in question:

In this case, I was encountering an error from the getSingleFromSomewhere() block (triggering the error in line 6). But, what wasn’t immediately clear to me was whether or not the outer subscribe() call would continue running or if it would be terminated as a result of the inner error.

I created a test that looked like this to try to uncover the answer:

The only change from the above code is the call to emitValueOnOuterObservable() on line 8. I wanted to verify if I explicitly emitted a success value for the outer observable if it would go through, or if it would somehow know that an error had occurred on the inner observable and would therefore no longer be running.

To my delight, even though an error occurs in the inner subscribe() block, the outer subscription keeps running, and I was able to see the "Outer value" log statement show up.

In hindsight, this makes sense, but the lesson here is if you’re not sure how something works, now is the right time to learn! Use the debugger, add print statements, or even just look through the code to gain an understanding of how it operates. And, if you get really stuck, look for documentation or ask a friend!

Also, it was not helpful in this case, but if you’re ever struggling with understanding how a particular Rx command works, be sure to take a look at RxMarbles, an interactive marble diagram site that lets you play with inputs/outputs so you can observe how they behave in different scenarios!

Do you have other nuggets of RxJava knowledge you’d like to share? Leave a comment below! And, please follow me on Medium if you’re interested in being notified of future tidbits.

Interested in joining the awesome team here at Intrepid? We’re hiring!

This tidbit was discovered on October 24, 2019.

Top comments (0)