Difference between Mono.then and Mono.flatMap/map

1.9k Views Asked by At

Say I want to call a webservice1 and then call webservice2 if the first was successful.

I can do the following (just indicative psuedo code) :-

Mono.just(reqObj)
.flatMap(r -> callServiceA())
.then(() -> callServiceB())

or

Mono.just(reqObj)
.flatMap(r -> callServiceA())
.flatMap(f -> callServiceB())

What is the difference between the two, when using the mono.just() for a single element?

2

There are 2 best solutions below

1
On BEST ANSWER

flatMap should be used for non-blocking operations, or in short anything which returns back Mono, Flux.

map should be used when you want to do the transformation of an object /data in fixed time. The operations which are done synchronously.

For ex:

return Mono.just(Person("name", "age:12"))
    .map { person ->
        EnhancedPerson(person, "id-set", "savedInDb")
    }.flatMap { person ->
        reactiveMongoDb.save(person)
    }

then should be used when you want to ignore element from previous Mono and want the stream to be finised

0
On

Here's a detailed explanation from @MuratOzkan

Copy pasting the TL DR answer:

If you care about the result of the previous computation, you can use map(), flatMap() or other map variant. Otherwise, if you just want the previous stream finished, use then().

In your example, looks like your service calls do not require the input of the upstream, then you could use this instead:

Mono.just(reqObj)
.then(() -> callServiceA())
.then(() -> callServiceB())