Spring / Spring Webflux Interview questions
Difference between Mono.just() and Mono.defer().
The key difference between Mono.just() and Mono.defer() lies in when the value or the Mono pipeline is generated.
Mono.just() creates a Mono eagerly at the time of code assembly, capturing the value immediately. The same value is emitted to all subsequent subscribers.
Mono.defer() creates a new Mono instance for each subscriber, with the value being generated at the moment of subscription.
| Feature | Mono.just() | Mono.defer() |
|---|---|---|
| Execution Time | Eager: Value is computed when Mono.just() is called (during pipeline assembly). |
Lazy: Value is computed only when a subscriber subscribes (at subscription time). |
| Value to Subscribers | All subscribers receive the exact same pre-computed value. | Each subscriber can receive a different, freshly computed value. |
| Input Type | Takes a direct value T (must be non-null). |
Takes a Supplier<Mono<T>> (a function that returns a Mono). |
| Use Case | Use for static, constant, or already-computed non-null values. | Use for dynamic values, values that need to be up-to-date, or when the value fetching has side effects or can fail. |
In the Mono.just() case, if a delay occurs between subscriptions, all subscribers still receive the original timestamp. With Mono.defer(), each subscription triggers the System.currentTimeMillis() call again, ensuring the most current timestamp is used.
// Using Mono.just() Mono<Long> justMono = Mono.just(System.currentTimeMillis()); // Time captured NOW, when 'justMono' is created. // Subscribe multiple times: all print the same time justMono.subscribe(time -> System.out.println("Just Time: " + time)); justMono.subscribe(time -> System.out.println("Just Time: " + time)); // Using Mono.defer() Mono<Long> deferMono = Mono.defer(() -> Mono.just(System.currentTimeMillis())); // The supplier (lambda) is executed only upon subscription. // Subscribe multiple times: each can print a different time deferMono.subscribe(time -> System.out.println("Defer Time: " + time)); // Small delay here deferMono.subscribe(time -> System.out.println("Defer Time: " + time));
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
