Skip to main content

Posts

Showing posts from July, 2017

Eager subscription - RxJava FAQ

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.
Observables and Flowables are lazy by nature. This means no matter how heavy or long-running logic you place inside your Flowable, it will get evaluated only when someone subscribes. And also as many times as someone subscribes. This is illustrated by the following code snippet:

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"); Such Observable or Flowable will inevitably print:

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