Reputation: 781
I am absoluteltly new to reactor.
My flatMap, doOnNext, doFinally is not getting called for inner Mono.
I added the sample test and output of it which depicts the problem. It wont getting called even if I interchange getMeIntegerMono2
with getMeStringMono
,
is there anything wrong i am doing ?
@Test
public void prodBug() {
System.out.println(Final());
}
String Final(){
final String[] val = new String[1];
System.out.println("1 - "+Thread.currentThread().getName());
Mono<Integer> intMono =
getMeIntegerMono("2")
.doOnNext(integer -> {
getMeIntegerMono2("21")
.flatMap(s -> getMeStringMono(String.valueOf(s)));
});
System.out.println("2 - "+Thread.currentThread().getName());
intMono.subscribe(integer -> {
val[0] =String.valueOf(integer);
});
System.out.println("3 - "+Thread.currentThread().getName());
return val[0];
}
Mono<String> getMeStringMono(String val){
System.out.println("String Mono - "+Thread.currentThread().getName());
return Mono.just(val);
}
Mono<Integer> getMeIntegerMono(String val){
System.out.println("Integer Mono - "+Thread.currentThread().getName());
return Mono.just(Integer.parseInt(val));
}
Mono<Integer> getMeIntegerMono2(String val){
System.out.println("Integer Mono2 - "+Thread.currentThread().getName());
return Mono.just(Integer.parseInt(val));
}
the output is
1 - main
Integer Mono - main
2 - main
Integer Mono2 - main
3 - main
2
Process finished with exit code 0
Upvotes: 2
Views: 12519
Reputation: 887
There's a few issues with your code.
In Reactor, nothing happens until you subscribe. That is to say just creating a Mono doesn't do anything. In the function you pass to doOnNext
, you create a Mono which is never subscribed to. Because of that, the function you pass to flatMap
will never be invoked. Try to use flatMap
instead of doOnNext
(you will need to fiddle with the types a bit to get it to work).
One problem with the way you are testing this comes from the difference between "assembly time" and "execution time." In all of your getMe*
methods, you immediately print something and then return a Mono. This actually is misleading when debugging because the printing will happen during assembly time, even if the returned Mono is never executed. You can perform the side effects at execution time instead using Mono.defer()
or Mono.fromSupplier()
.
The technique of using an array to get around Java's restrictions on variables and lambdas is poor practice and while it may work in this case, you should get out of the habit as it's very fragile. To understand why, imagine that some Mono in your chain does an expensive operation in another thread. This means the function you pass to subscribe
will be invoked after Final()
has already returned.
Upvotes: 4