How to debug RxJava Observable method calls/chains

As a brief note to self, when you need to debug a chain of RxJava Observable method calls, you can use the doOnNext method to log the current values or print them to STDOUT or STDERR with println. Here’s an example from RxJava For Android Developers, where the debug output is logged with the Android Log.d method:

Observable<Boolean> isFormValidObservable = ValidationUtils.and(
    isCreditCardNumberValid
        .doOnNext(value -> Log.d(
            TAG,
            "isCreditCardNumberValid: " + value
        ),
        isCheckSumValid,
        isCvcCodeValid
);

Here’s a second example from this grokkingandroid.com post that shows several doOnNext calls in one Observable chain:

Observable someObservable = Observable
    .from(Arrays.asList(new Integer[]{2, 3, 5, 7, 11}))
    .doOnNext(System.out::println)
    .filter(prime -> prime % 2 != 0)
    .doOnNext(System.out::println)
    .count()
    .doOnNext(System.out::println)
    .map(number -> String.format("Contains %d elements", number));

doOnNext is cool because it lets you perform side effects like debugging/logging without breaking the chain of method calls on the Observable.