0

I'm new to Spring WebFlux and do not fully understand the Mono.when(). The following code does not work as expected:

List<Mono<Void>> results= ....;
 
String textVar = "my text";

processors.forEach(p -> {
    Mono<Object> restResponseMono = client.getSomething();
    results.add(restResponseMono.doOnNext(resp -> {
      textVar = textVar + resp.getText();
    }).then());
});


Mono.when(results).then(
  //here it would expect modification of 'textVar'
  Mono.just(textVar);
)


After calling the Mono.when(results).then(...) I would expect all my changes to be applied to the textVar because in the docu it is written:

[...Aggregate given publishers into a new Mono that will befulfilled when all of the given Publishers have completed....]

And the restResponseMono.then() should also wait until everything is completed. So I do not know exactly where is my lack of understanding.

JimBob
  • 156
  • 1
  • 15
  • check this answer: https://stackoverflow.com/a/57877616/6051176 also, it's not really good idea to rely on side effects (modifying/accessing external variable) in reactive operators, you should rather write this logic in a single chain and rely on output of operators – Martin Tarjányi Apr 02 '21 at 18:41
  • Solved it with the following code: `return Flux.fromIterable(processors) .flatMapSequential(processor -> { return processor.process(textVar); }).last() .flatMap(textVar-> { return Mono.just(textVar); });` It's doing the job but somehow it does not feel right. Isn't there a pattern for WebFlux? I mean working with some kind of processing chain/pipeline on an object is not that uncommon I think. – JimBob Apr 05 '21 at 20:34

1 Answers1

0

Publishers in the when parameter,When subscribe automatically subscribes. The way it works is simply this.

            Flux<Integer> m1 = Flux.just(1,2).doOnNext(e -> System.out.println("M1 doOnNext: " + e));
            Mono<Integer> m2 = Mono.just(12).doOnSuccess(e -> System.out.println("M2 doOnSuccess: " + e));

            Mono<String> mono = Mono.when(m1,m2).then(Mono.just("STR")).doOnSuccess(e -> System.out.println("_________when doOnSuccess: " + e));
            mono.log().subscribe(System.out::println, Exception::new, () -> System.out.println("Completed2."));
Ogün
  • 97
  • 2
  • 10