zhuochen shen
zhuochen shen

Reputation: 1753

Mono<List<T>> difference with Flux<T> in Spring webflux

My understand is Mono<List<T>> is a synchronized Flux<T> and Flux could not be a rest api response.

Am I right?

If not, what's the different between Mono<List<T>> and Flux<T> or could a Flux could be a rest api response in some where ?

Upvotes: 21

Views: 17677

Answers (2)

nanachimi
nanachimi

Reputation: 416

  • Mono<List<T>> will emit zero or maximal one list of item of type T.
  • Flux<T>will emit zero or many items of type T

Momo wraps is bounded and Flux is not.

Mono<List<T>> is a synchronized Flux

Mono and Flux are both a Reactor implementation of a Publisher interface specified in a Reactive Stream Specification.

Reactor Mono class: public abstract class Mono<T> implements Publisher<T> {...}

Reactor Mono class: public abstract class Flux<T> implements Publisher<T> {...}

Flux could not be a rest api response. Of course Fluxcan be used as response type of REST API. By using Flux as return type you can easily switch from asynchronous to synchronous processing . If you use Spring Boot you can even stream data to your consumer just by changing the Content-Type of you API endpoint to application/stream+json as mention by @Brian.

Note that Flux and Mono are non blocking which means that you working threads (computer resources) can be used more efficiently.

Upvotes: 2

Brian Clozel
Brian Clozel

Reputation: 59231

  • as a return type, Mono<List<T>> means that you'll get asynchronously a full list of T elements in one shot.
  • Flux<T> means that you'll get zero to many T elements, possibly one by one as they come.

If you're getting such return types from an HTTP client such as WebClient, Mono<List<T>> and Flux<T> might be more or less equivalent from a runtime perspective, if the returned Content-Type is for example "application/json". In this case, the decoder will deserialize the response in one shot. The only different is, Flux<T> provides more interesting operators and you can always collectList and fall back to a Mono<List>.

On the other hand, if the returned Content-Type is a streaming one, for example "application/stream+json" then this definitely has an impact as you'll get the elements one by one as they come. In fact, if the returned stream is infinite, choosing Flux<T> is very important as the other one will never complete.

Upvotes: 35

Related Questions