关于java:Mono.then和Mono.flatMap / map之间的区别

Difference between Mono.then and Mono.flatMap/map

假设我要先调用webservice1,然后再调用webservice2(如果第一个成功)。

我可以执行以下操作(仅指示伪代码):-

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

要么

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

将mono.just()用于单个元素时,两者之间有什么区别?


flatMap应该用于非阻塞操作,或者简而言之,它会返回Mono,Flux。

如果要在固定时间内进行对象/ data的转换,应使用map。 同步完成的操作。

例如:

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

当您要忽略上一个Mono的元素并希望对流进行精化时,应使用then


这是@MuratOzkan的详细说明

复制粘贴TL DR答案:

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().

在您的示例中,您的服务调用看起来不需要上游的输入,那么您可以使用它:

1
2
3
Mono.just(reqObj)
.then(() -> callServiceA())
.then(() -> callServiceB())