1. Overview
1.概述
In our Intro to Project Reactor, we learned about Mono<T>, which is a publisher of an instance of type T.
在我们的Project Reactor入门中,我们学习了Mono<T>,它是一个类型T的实例的发布器。
In this quick tutorial, we’ll show both a blocking and a non-blocking way to extract T from the Mono: block and subscribe.
在这个快速教程中,我们将展示从Mono中提取T的阻塞式和非阻塞式方法。block和subscribe。
2. Blocking Way
2.阻挡方式
In general, Mono completes successfully by emitting an element at some point in time.
一般来说,Mono通过在某个时间点上发射一个元素而成功完成。
Let’s start with an example publisher Mono<String>:
让我们从一个出版商的例子开始Mono<String>。
Mono<String> blockingHelloWorld() {
return Mono.just("Hello world!");
}
String result = blockingHelloWorld().block();
assertEquals("Hello world!", result);
Here, we’re blocking the execution as long as the publisher doesn’t emit the value. However, it can take any amount of time to finish.
在这里,只要发布者不发出数值,我们就会阻断执行。然而,它可以花费任何时间来完成。
To get more control, let’s set an explicit duration:
为了得到更多的控制,让我们设置一个明确的期限。
String result = blockingHelloWorld().block(Duration.of(1000, ChronoUnit.MILLIS));
assertEquals(expected, result);
If the publisher doesn’t emit a value within the set duration, a RuntimeException is thrown.
如果发布者没有在设定的持续时间内发射一个值,就会抛出一个RuntimeException。
Additionally, Mono could be empty and the block() method above will return null. We can, instead, make use of blockOptional in that case:
此外,Mono可能是空的,上面的block()方法将返回null。在这种情况下,我们可以使用blockOptional。
Optional<String> result = Mono.<String>empty().blockOptional();
assertEquals(Optional.empty(), result);
In general, blocking contradicts the principles of reactive programming. It’s highly discouraged to block the execution in reactive applications.
一般来说,阻塞与反应式编程的原则相矛盾。在反应式应用程序中,非常不鼓励阻塞执行。
So, now let’s see how to get the value in a non-blocking way.
所以,现在让我们看看如何以非阻塞的方式获得价值。
3. Non-Blocking Way
3.非阻塞性方式
First of all, we should subscribe in a non-blocking way using the subscribe() method. Also, we’ll specify the consumer of the final value:
首先,我们应该使用subscribe()方法以非阻塞的方式进行订阅。另外,我们要指定最终值的消费者。
blockingHelloWorld()
.subscribe(result -> assertEquals(expected, result));
Here, even if it takes some time to produce the value, the execution immediately continues without blocking on the subscribe() call.
在这里,即使产生值需要一些时间,执行也会立即继续,不会在subscribe()调用上阻塞。
In some cases, we want to consume the value in intermediate steps. Therefore, we can use an operator to add behavior:
在某些情况下,我们想在中间步骤中消耗价值。因此,我们可以使用一个操作符来增加行为。
blockingHelloWorld()
.doOnNext(result -> assertEquals(expected, result))
.subscribe();
4. Conclusion
4.总结
In this short article, we have explored two ways of consuming a value produced by Mono<String>.
在这篇短文中,我们探讨了两种消耗由Mono<String>产生的值的方法。
As always, the code example can be found over on GitHub.
一如既往,代码示例可以在GitHub上找到over。