



Warsaw center from Park Szczęśliwicki

Observable

Flowable

Flowable

private static String slow() throws InterruptedException { logger.info("Running"); TimeUnit.SECONDS.sleep(1); return "abc"; } //... Flowable<String> flo = Flowable.fromCallable(this::slow); logger.info("Created"); flo.subscribe(); flo.subscribe(); logger.info("Done");

Observable

Flowable

19:37:57.368 [main] - Created 19:37:57.379 [main] - Running 19:37:58.383 [main] - Running 19:37:59.388 [main] - Done

sleep()

main

subscribeOn()

Totally eager evaluation

Flowable

Flowable<String> eager() { final String slow = slow(); return Flowable.just(slow); }

subscribeOn()

eager()

Flowable

Using cache() operator

cache()

Flowable<String> eager3() throws InterruptedException { final Flowable<String> cached = Flowable .fromCallable(this::slow) .cache(); cached.subscribe(); return cached; }

Flowable

cache()

Subscriber

cache()

subscribe()

slow()

subscribe()

Scheduler

Flowable

subscribeOn()

Flowable<String> eager3() throws InterruptedException { final Flowable<String> cached = Flowable .fromCallable(this::slow) .subscribeOn(justDontAlwaysUse_Schedulers.io()) .cache(); cached.subscribe(); return cached; }

Schedulers.io()

Error handling

slow()

System.err

OnErrorNotImplementedException

doOnError()

OnErrorNotImplementedException

onError

subscribe()

Flowable<String> eager3() throws InterruptedException { final Flowable<String> cached = Flowable .fromCallable(this::slow) .cache(); cached.subscribe( x -> {/* ignore */}, e -> logger.error("Prepopulation error", e)); return cached; }

subscribe()

Flowable

observe()

toObservable()

While teaching and mentoring RxJava, as well as after authoring a book , I noticed some areas are especially problematic. I decided to publish a bunch of short tips that address most common pitfalls. This is the first part.s ands are lazy by nature. This means no matter how heavy or long-running logic you place inside your, it will get evaluated only when someone subscribes. And also as many times as someone subscribes. This is illustrated by the following code snippet:Suchorwill inevitably print:Notice that you pay the price oftwice (double subscription). Moreover all logic runs in client () thread, there is no implicit threading in RxJava unless requested withor implicitly available with asynchronous streams. The question is: can we force running subscription logic eagerly so that whenever someone subscribes the stream is already precomputed or at least the computation started?The most obvious, but flawed solution is to eagerly compute whatever the stream returns and simply wrap it with a fixedUnfortunately this substantially defeats the purpose of RxJava. First of all operators likeno longer work and it becomes impossible to off-load computation to a different thread. Even worse, even thoughreturns ait will always, by definition, block client thread. It is harder to reason, compose and manage such streams. You should generally avoid such pattern and prefer lazy-loading even when eager evaluation is necessary.The next example does just that withoperator:The idea is simple: wrap computation with lazyand make it cached. Whatoperator does is it remembers all emitted events upon first subscription so that when secondappears, it will receive the same cached sequence of events. Howeveroperator (like most others) is lazy so we must forcibly subscribe for the first time. Callingwill prepopulate cache, moreover if second subscriber appears beforecomputation finishes, it will wait for it as well rather than starting it for the second time.This solution works but keep in mind thatwill actually block because nowas involved. If you want to prepopulate yourin background, tryYes, usingis problematic and hard to maintain on production systems so please avoid it in favor of custom thread pools.Sadly it's surprisingly easy to swallow exceptions in RxJava. That's what can happen in our last example ifmethod fails. The exception isn't swallowed entirely, but by default, if no-one was interested, it's stack trace is printed on. Also unhandled exception is wrapped with. Not very convenient and most likely lost if you are doing any form of centralized logging. You can useoperator for logging but it still passes exception downstream and RxJava considers it unhandled as well, one more time wrapping with. So let's implementcallback inWe don't want to handle actual events, just errors in. At this point you can safely return such. It's eager and chances are that whenever yuo subscribe to it, data will already be available. Notice that for examplemethod from Hystrix is eager as well, as opposed to, which is lazy. The choice is yours.