Open In App

Difference Between Mono and Flux in Spring WebFlux

Last Updated : 24 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Spring WebFlux is a part of the Spring Framework that provides reactive programming support for web applications. It introduces reactive types like Mono and Flux publishers which are fundamental to Its programming model. Mono and Flux play a crucial role in reactive programming.

In this article, we will explore Mono vs Flux.

Mono

  • Creation: A Mono can be created by using static methods like Mono.just() or Mono.empty() or Mono.error()
  • Subscription: The subscriber subscribes to the Mono triggering the execution of the pipeline.
  • Emission: The Mono publisher emits zero or one item followed by an onComplete or onError signals
  • Operators: Various operators can transform the emitted item, handle errors, or perform side-effects

Advantages:

  • Simplicity: Ideal for operations that return a single result or none.
  • Performance: Efficient handling of single-value streams with minimal overhead.
  • Error Handling: Comprehensive error handling capabilities with operators like onErrorReturn and onErrorResume.

Flux

  • Creation: A Flux can be created by using static methods like Flux.just() or Flux.fromIterable() or Flux.range()
  • Subscription: The subscriber subscribes to the Flux triggering the execution of the pipeline.
  • Emission: The Mono publisher emits zero to N items followed by an onComplete or onError signals
  • Operators: Various operators can transform the emitted items, handle errors, buffer, window, or combine multiple Flux streams

Advantages:

  • Flexibility: Capable of handling multiple items, making it suitable for collections, streams, and real-time data.
  • Rich Operators: Extensive set of operators to manipulate and transform data streams, including buffer, window, merge, zip, etc.
  • Scalability: Efficiently manages large data streams with built-in Backpressure support.

Examples of Mono and Flux

Here we provide two different examples for Mono and Flux publishers. The Mono publisher can emits zero or one and The Flux publisher can emits zero to N events.

Example Program for Mono:

In this example, we created a Mono type publisher and It returns a String type mono object and The Mono publisher can emits only one event.

Java
package com.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import reactor.core.publisher.Mono;

@SpringBootApplication
public class PublishersApplication {

    public static void main(String[] args) {
        SpringApplication.run(PublishersApplication.class, args);
        
        Mono<String> greeting = Mono.just("Welcome to GeeksForGeeks");

        greeting.subscribe(
            System.out::println
        );
    }

}

Output:

Mono Output


Example Program for Flux:

In this example, we created a Flux type publisher and It returns a String type flux object and The Flux publisher can emits only zero to N events.

Java
package com.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import reactor.core.publisher.Flux;

@SpringBootApplication
public class PublishersApplication {

    public static void main(String[] args) {
        SpringApplication.run(PublishersApplication.class, args);
        
        Flux<String> names = Flux.just("John", "Marry","Micky", "Hani");

        names.subscribe(
            System.out::println
        );
    }

}

Output:

Flux Output


Difference Between Mono and Flux

Below is the difference table of Mono and Flux.

Aspect

Mono

Flux

Definition

Represents 0 or 1 item.

Represents 0 to N items.

Use Cases

Single result. Ex: a database lookup for one record.

Multiple results. Ex: database query returning a list.

Common Operations

map, flatMap, filter, then

map, flatMap, filter, take, skip, merge, zip

Return Types

Mono<T>

Flux<T>

Example 1 (Creating)

Mono.just("Hello, Spring WebFlux!")

Flux.just("Item 1", "Item 2", "Item 3")

Example 2 (Handling HTTP Requests)

Mono<ServerResponse> handling single item response

Mono<ServerResponse> handling multiple item response

Example 3 (REST Controller)

@GetMapping("/single") public Mono<String> getSingleItem() { return Mono.just("Single Item"); }

@GetMapping("/multiple") public Flux<String> getMultipleItems() { return Flux.just("Item 1", "Item 2", "Item 3"); }

Publisher Type

Single-emission publisher

Multi-emission publisher

Life cycle Events

onNext, onError, onComplete

onNext, onError, onComplete

Reactive Stream Support

Backpressure handling

Backpressure handling

Error Handling

onErrorReturn, onErrorResume, onErrorMap

onErrorReturn, onErrorResume, onErrorMap

Cold Publisher

Emits items only when subscribed

Emits items only when subscribed



Similar Reads