Mono.defer()有什么作用? [英] what does Mono.defer() do?

查看:497
本文介绍了Mono.defer()有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一些Spring webflux代码中遇到了Mono.defer()

I've come across Mono.defer() in some Spring webflux code

我在文档中查找了该方法,但不理解其中的解释:

I looked up the method in the docs but don't understand the explanation:

"创建一个Mono提供程序,该提供程序将提供要订阅的目标Mono对于每个下游订阅者"

"Create a Mono provider that will supply a target Mono to subscribe to for each Subscriber downstream"

请给我一个解释和一个例子.我可能会参考一堆Reactor示例代码(它们的单元测试?)的地方.

please could I have an explanation and an example. Is there a place with a bunch of Reactor example code (their unit tests?) that I might reference.

谢谢

推荐答案

这有点过分简化,但是从概念上讲,Reactor的来源要么是懒惰的,要么是渴望的.诸如HTTP请求之类的更高级的请求将被懒惰地评估.另一方面,最简单的方法是 Mono.just Flux.fromIterable .

It is a bit of an oversimplification but conceptually Reactor sources are either lazy or eager. More advanced ones, like an HTTP request, are expected to be lazily evaluated. On the other side the most simple ones like Mono.just or Flux.fromIterable are eager.

通过这种方式,我的意思是调用 Mono.just(System.currentTimeMillis())将立即调用 currentTimeMillis()方法并捕获结果.订阅后,该结果仅由 Mono 发射.多次订阅也不会更改该值:

By that, I mean that calling Mono.just(System.currentTimeMillis()) will immediately invoke the currentTimeMillis() method and capture the result. Said result is only emitted by the Mono once it is subscribed to. Subscribing multiple times doesn't change the value either:

Mono<Long> clock = Mono.just(System.currentTimeMillis());
//time == t0

Thread.sleep(10_000);
//time == t10
clock.block(); //we use block for demonstration purposes, returns t0

Thread.sleep(7_000);
//time == t17
clock.block(); //we re-subscribe to clock, still returns t0

defer 运算符可让此源变得懒惰,每次有新订阅者时都重新评估lambda的内容:

The defer operator is there to make this source lazy, re-evaluating the content of the lambda each time there is a new subscriber:

Mono<Long> clock = Mono.defer(() -> Mono.just(System.currentTimeMillis()));
//time == t0

Thread.sleep(10_000);
//time == t10
clock.block(); //invoked currentTimeMillis() here and returns t10

Thread.sleep(7_000);
//time == t17
clock.block(); //invoke currentTimeMillis() once again here and returns t17

这篇关于Mono.defer()有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆