Sobes.tech
Middle

What is the difference between Mono and Flux in reactive programming?

sobes.tech AI

Answer from AI

Mono emits 0 or 1 element. Flux emits 0 or more elements (including infinitely many).

Usage examples:

  • Mono: Result of an operation on a single object (e.g., saving a record in a database, retrieving a single item by ID).
  • Flux: Stream of events (e.g., user clicks, data from a file, collection elements).
// Mono example: getting a single user
Mono<User> findUserById(Long userId) {
    return userRepository.findById(userId);
}
// Flux example: getting all users
Flux<User> findAllUsers() {
    return userRepository.findAll();
}

Main differences:

Characteristic Mono Flux
Number of elements 0 or 1 0 or more
Representation Represents a single event Represents a stream of events
Operations Applied to a single element Applied to a stream of elements