1

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?

Jerald Baker
  • 1,121
  • 1
  • 12
  • 48
  • Does this answer your question? [Should I use "then" or "flatMap" for control flow?](https://stackoverflow.com/questions/49710432/should-i-use-then-or-flatmap-for-control-flow) – daniu Jul 12 '20 at 20:29

2 Answers2

3

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

Liquidpie
  • 1,589
  • 2
  • 22
  • 32
  • 5
    also, since `then` acts on the `onComplete` signal it works including if the source is empty (as in `Flux.empty()`), whereas `map` and `flatMap` only trigger if there is an `onNext` signal. – Simon Baslé Jul 13 '20 at 07:59
1

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())
Codigo Morsa
  • 820
  • 7
  • 14