Is it possible to get the first element from flux without converting flux into stream?
How to extract data from Flux in Java? Another way would be using the Reactive Streams operators like onNext, flatMap, etc. In the below example, we are using the onNext() method to get data from Flux and print it. Note: We need to subscribe to the Publisher.
Instead of take(1) , you could use next() . This will transform the Flux into a valued Mono by taking the first emitted item, or an empty Mono if the Flux is empty itself.
A Flux object represents a reactive sequence of 0.. N items, while a Mono object represents a single-value-or-empty (0..1) result. This distinction carries a bit of semantic information into the type, indicating the rough cardinality of the asynchronous processing.
Subscribe to this Flux and block until the upstream signals its first value, completes or a timeout expires. Subscribe to this Flux and block indefinitely until the upstream signals its last value or completes.
Alternatively to take(1)
, if you need a Mono<T>
that represents the first element of the Flux<T>
you can use .next()
.
Or if you need the i-th element, use .elementAt(i)
(must be sure that such an element exists though, unlike take
and next
which just return an empty publisher if not enough elements).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With