DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Java Stream API: 3 Things Every Developer Should Know About
  • How to Design Event Streams, Part 3
  • Process Mining Key Elements
  • How to Design Event Streams, Part 2

Trending

  • When Airflow Tasks Get Stuck in Queued: A Real-World Debugging Story
  • Designing AI Multi-Agent Systems in Java
  • Data Lake vs. Warehouse vs. Lakehouse vs. Mart: Choosing the Right Architecture for Your Business
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  1. DZone
  2. Coding
  3. JavaScript
  4. Eager Subscription: RxJava FAQs

Eager Subscription: RxJava FAQs

Learning RxJava can be a challenge, what with it being a fairly substantial shift in how you think. In this post, we take a look at some FAQs that come up.

By 
Tomasz Nurkiewicz user avatar
Tomasz Nurkiewicz
DZone Core CORE ·
Aug. 03, 17 · Opinion
Likes (7)
Comment
Save
Tweet
Share
7.0K Views

Join the DZone community and get the full member experience.

Join For Free

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 the most common pitfalls. This is the first part.

Observables and Flowables are lazy by nature. This means that no matter what 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 an 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


Notice that you pay the price of sleep() twice (double subscription). Moreover, all logic runs in the client (main) thread — there is no implicit threading in RxJava unless requested with subscribeOn() or 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 has started?

Totally Eager Evaluation

The most obvious, but flawed, solution is to eagerly compute whatever the stream returns and simply wrap it with a fixed Flowable:

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


Unfortunately, this substantially defeats the purpose of RxJava. First of all, operators like subscribeOn() no longer work and it becomes impossible to off-load computation to a different thread. Even worse, even though eager() returns a Flowable, it will always, by definition, block client threads. It is harder to reason, compose, and manage such streams. You should generally avoid such patterns and prefer lazy-loading, even when eager evaluation is necessary.

Using cache() Operator

The next example does just that with cache() operator:

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


The idea is simple: wrap computation with a lazy Flowable and make it cached. The cache() operator remembers all emitted events upon the first subscription so that when the second Subscriber appears, it will receive the same cached sequence of events. However, the cache() operator (like most others) is lazy, so we must forcibly subscribe for the first time. Calling subscribe() will prepopulate the cache. Moreover, if the second subscriber appears before the slow() computation finishes, it will wait for it as well, rather than starting it for the second time.

This solution works, but keep in mind that subscribe() will actually block because no Scheduler was involved. If you want to prepopulate your Flowable in the background, try subscribeOn():

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


Yes, using Schedulers.io() is problematic and hard to maintain on production systems, so please avoid it in favor of custom thread pools.

Error Handling

Sadly it's surprisingly easy to swallow exceptions in RxJava. That's what can happen in our last example if the slow() method fails. The exception isn't swallowed entirely, but by default, if no one was interested, its stack trace is printed on System.err. Also, the unhandled exception is wrapped with OnErrorNotImplementedException. Not very convenient and most likely lost if you are doing any form of centralized logging. You can use the doOnError() operator for logging, but it still passes the exception downstream, and RxJava considers it unhandled as well, once more time wrapping with OnErrorNotImplementedException. So let's implement an onError callback in 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;
}


We don't want to handle actual events, just errors in subscribe(). At this poin, you can safely return such Flowables. It's eager and, chances are, that whenever you subscribe to it, data will already be available. Notice that, for example, the observe() method from Hystrix is eager as well, as opposed to toObservable(), which is lazy. The choice is yours.

Operator (extension) guidelines Stream (computing) Lazy loading Event Evaluation Blocks IT

Published at DZone with permission of Tomasz Nurkiewicz, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java Stream API: 3 Things Every Developer Should Know About
  • How to Design Event Streams, Part 3
  • Process Mining Key Elements
  • How to Design Event Streams, Part 2

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!