Is it possible to get the first element from flux without converting flux into stream?
Asked
Active
Viewed 2.7k times
3 Answers
24
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).

Simon Baslé
- 27,105
- 5
- 69
- 70
-
1Thanks @Simon for you reply. I idea here is to sort the Flux first and then get the first element. After seeing the docs I can achieve the same by using reduce on the flux as below. Flux.just(1, 2, 3) .reduce((o1, o2) -> { if (o1 - o2 < 0) { return o1; } return o2; }) – akreddy.21 Mar 07 '19 at 06:18
4
Flux.range(1,10).take(1)
should do the trick (the range(...)
part here is only to emit some sample values; if you blockFirst()
or subscribe()
to the stream, you should see '1')

Mikhail Kholodkov
- 23,642
- 17
- 61
- 78

Frischling
- 2,100
- 14
- 34
0
Also the easiest: you can convert your Flux
to Mono
using Mono.from()
Mono<T> mono = Mono.from(flux);
It takes the first element of flux or completes with empty if flux has not emitted any element.

kerbermeister
- 2,985
- 3
- 11
- 30