简体   繁体   English

Mono.then 和 Mono.flatMap/map 之间的区别

[英]Difference between Mono.then and Mono.flatMap/map

Say I want to call a webservice1 and then call webservice2 if the first was successful.假设我想调用 webservice1,如果第一个成功则调用 webservice2。

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?将 mono.just() 用于单个元素时,两者有什么区别?

flatMap should be used for non-blocking operations, or in short anything which returns back Mono, Flux. flatMap应该用于非阻塞操作,或者简而言之,任何返回 Mono、Flux 的操作。

map should be used when you want to do the transformation of an object /data in fixed time. map用于在固定时间内对 object /data 进行转换。 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当您想忽略以前 Mono 中的元素并希望完成 stream 时,应该使用then

Here's a detailed explanation from @MuratOzkan 这是来自@MuratOzkan 的详细解释

Copy pasting the TL DR answer:复制粘贴 TL DR 答案:

If you care about the result of the previous computation, you can use map(), flatMap() or other map variant.如果您关心之前计算的结果,可以使用 map()、flatMap() 或其他 map 变体。 Otherwise, if you just want the previous stream finished, use then().否则,如果您只想完成之前的 stream,请使用 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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM