Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactor will operations on a flux occur in order?

If I have two flatmaps on a flux will the they always execute in sequence

Flux.just(1,2,3,4)
    .flatMap(...) 
    .flatMap(...) // Will this always execute 2nd?
like image 505
Adam Sedgwick Avatar asked Dec 11 '25 22:12

Adam Sedgwick


2 Answers

It depends on what exactly you mean - specifics are important here.

For any given element the answer is yes - it will be processed by the first flatMap call, then the results of that flatMap call processed by the second flatMap call. Recall that operators in reactor, similar to vanilla Java streams, are chained - so there's no sensible way they could ever operate out of sequence.

For all elements in total though, no - as in it won't process the first flatMap call for all 4 elements, then process the second flatMap call for all 4 elements - each element is treated independently. When you consider that a Flux is analogous to a stream of elements that may have no end, rather than a defined, bounded collection, it wouldn't make much sense if it didn't behave this way.

like image 96
Michael Berry Avatar answered Dec 14 '25 11:12

Michael Berry


Let's consider these small examples :

Flux.just(3, 2, 1)
  .flatMap(e -> {
    System.out.println("First FlatMap : " + e);
    return Mono.just(e).delayElement(Duration.ofMillis(e * 100));
  })
  .flatMap(e -> {
    System.out.println("Second FlatMap : " + e);
    return Mono.just(e);
  })
  .blockLast();

/*
First FlatMap : 3
First FlatMap : 2
First FlatMap : 1
Second FlatMap : 1
Second FlatMap : 2
Second FlatMap : 3
*/
Flux.just(3, 2, 1)
  .flatMap(e -> {
    System.out.println("First FlatMap : " + e);
    return Mono.just(e);
  })
  .flatMap(e -> {
    System.out.println("Second FlatMap : " + e);
    return Mono.just(e);
  })
  .blockLast();

/*
First FlatMap : 3
Second FlatMap : 3
First FlatMap : 2
Second FlatMap : 2
First FlatMap : 1
Second FlatMap : 1
*/

We can say an operator process the elements in the order they came in.

like image 25
Olivier Boissé Avatar answered Dec 14 '25 13:12

Olivier Boissé