Valahu
Valahu

Reputation: 833

Convert from Flux to Mono

How can I convert from a Flux with 1 element to a Mono?

Flux.fromArray(arrayOf(1,2,1,1,1,2))
                .distinct()
                .take(1)

How do I make this a Mono(1)?

Upvotes: 57

Views: 95976

Answers (4)

kerbermeister
kerbermeister

Reputation: 4221

Also the very simple way is to use Mono.from()

Mono<Integer> mono = Mono.from(flux);

If your flux has more than one element, then it will just take the first element emitted by the flux.

Upvotes: 2

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

Here is a list:

  • Flux#single will work if there is one element from Flux. Eg: flux.take(1).single();

  • Flux#next will get you the first element. Eg: flux.next();

  • Flux#last for last element. Eg: flux.last();

  • Flux#singleOrEmpty is similar to Optional. Eg: flux.take(0).singleOrEmpty();

  • Flux#collect, it depends on use case.

      flux.collect(Collectors.reducing((i1, i2) -> i1))
          .map(op -> op.get());
    
  • Flux#elementAt for i'th index. Eg: flux.elementAt(1);

  • Flux#shareNext for first found element. flux.shareNext();

  • Flux#reduce for reduction op. Eg: flux.reduce((i1,i2) -> i1);

Upvotes: 50

deepak kumar
deepak kumar

Reputation: 11

Or,you could use single() on the filtered Flux

Upvotes: 1

Simon Basl&#233;
Simon Basl&#233;

Reputation: 28301

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.

Upvotes: 100

Related Questions