Prev Next

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));

More Related questions...

Show more question and Answers...


Comments & Discussions