flatMap() vs subscribe() in Spring webflux
Asked Answered
V

1

8

I am a newbie to Spring WebFlux and trying to convert my spring MVC application to webflux. I return a Mono mono from my service :

    List<Store> stores = new ArrayList();

When I do:

    mono.subscribe(stores::addAll);
    dataexchange.put("stores", stores);
    return Mono.just(dataexchange);

Then stores is populated as empty list in response. However, I can verify that subscribe() is working after returning response.

When I do :

    return mono.flatmap( (response) -> {
        dataexchange.put("stores", response));
        return Mono.just(dataexchange);
    });

Then stores is populated in the response.

Can someone please explain me what is the difference between the two? Is flatMap blocking? Thanks in advance !

Vermiculation answered 12/2, 2019 at 10:25 Comment(0)
P
9
mono.subscribe(stores::addAll);

is asynchronous. That means, you tell the mono that it can now start evaluating.

What you do is continue processing stores right away - with a huge chance that the Mono hasn't evaluated yet.

So, how can you fix this?

You can block until the Mono has completed:

mono.doOnNext(stores::addAll).block()

Of course, this defeats the purpose of reactive programming. You are blocking the main thread until an action completes, which can be achieved without Reactor in a much simpler fashion.


The right way is to change the rest of your code to be reactive too, from head to toe. This is similar to your second example, where your call to dataexchange is part of the Mono, thus being evaluated asynchronously, too.

The important lesson to be learned is that operations like map or flatMap are not operating on the result of the Mono, but create a new Mono that adds another transformation to the execution of the original Mono. As long as the Mono doesn't evaluate, the flatMap or map operations are not actually doing anything.


I hope this helps.

Pettitoes answered 12/2, 2019 at 12:31 Comment(5)
So, that means that flaptmap isn't blocking? Also, I have read in a number of articles that "Nothing happens until you subscribe" , i.e. no data flow is available until you subscribe. Then how does flatmap work without subscribe() ?Vermiculation
@Vermiculation I can't tell from your example where you return your Mono to, but it absolutely shouldn't.Pettitoes
I am returning this mono directly from controller. Can you please answer why flatmap() works without subscribe()?Vermiculation
@Vermiculation it doesn't. Try it in a sandbox environment (without any controllers and other side effects). I think Spring handles the Mono when you return it by subscribing to it.Pettitoes
I was facing the same issue but doing a search in documentation of mongoDB using reactive driver. There are an example using CountDownLatch. After use the CountDownLatch I can see all steps from log of Webflux. Before I can`tSchmitt

© 2022 - 2024 — McMap. All rights reserved.