Adam Sedgwick
Adam Sedgwick

Reputation: 43

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?

Upvotes: 3

Views: 1696

Answers (2)

Olivier Boissé
Olivier Boissé

Reputation: 18083

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.

Upvotes: 1

Michael Berry
Michael Berry

Reputation: 72254

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.

Upvotes: 4

Related Questions