'Understanding Mono.when
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.
Solution 1:[1]
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."));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ogün |