翻譯自:https://tech.io/playgrounds/929/reactive-programming-with-reactor-3/Mono
Mono
Description
A Mono<T>
is a Reactive Streams Publisher
, also augmented with a lot of operators
that can be used to generate, transform, orchestrate Mono sequences.
Mono是一種反應(yīng)流發(fā)布者,還增加了許多運(yùn)算符,可用于生成、轉(zhuǎn)換和編排Mono序列。
It is a specialization of Flux
that can emit at most 1 <T> element:
a Mono is either valued (complete with element), empty (complete without element)
or failed (error).
它是Flux的特例,最多可以發(fā)射1個(gè)元素:Mono要么有值(帶元素完成),要么為空(無(wú)元素完成),要么為失敗(錯(cuò)誤)。
A Mono<Void>
can be used in cases where only the completion signal is interesting
(the Reactive Streams equivalent of a Runnable
task completing).
在只對(duì)完成信號(hào)感興趣的情況下(相當(dāng)于Runnable任務(wù)完成的反應(yīng)流),可以使用Mono<Void>。
Like for Flux
, the operators can be used to define an asynchronous pipeline
which will be materialized anew for each Subscription
.
與Flux一樣,可以使用運(yùn)算符定義異步管道,該管道將針對(duì)每個(gè)訂閱重新具體化。
Note that some API that change the sequence's cardinality will return a Flux
(and vice-versa, APIs that reduce the cardinality to 1 in a Flux
return a Mono
).
請(qǐng)注意,一些更改序列基數(shù)的API將返回Flux(反之亦然,在Flux中將基數(shù)減少到1的API將返回Mono)。
Mono
in action:
Mono.firstWithValue(
Mono.just(1).map(integer -> "foo" + integer),
Mono.delay(Duration.ofMillis(100)).thenReturn("bar")
)
.subscribe(System.out::println);
Practice
As for the Flux let's return a empty Mono
using the static factory.
就像Flux,讓我們使用靜態(tài)工廠返回一個(gè)空Mono。
// Return an empty Mono
Mono<String> emptyMono() {
return Mono.empty();
}
Now, we will try to create a Mono
which never emits anything.
Unlike empty()
, it won't even emit an onComplete
event.
現(xiàn)在,我們將嘗試創(chuàng)建一個(gè)從不發(fā)射任何東西的Mono。與empty()不同,它甚至不會(huì)發(fā)出onComplete事件。
// Return a Mono that never emits any signal
Mono<String> monoWithNoSignal() {
return Mono.never();
}
Like Flux
, you can create a Mono
from an available (unique) value.
與Flux一樣,您可以從可用(唯一)值創(chuàng)建Mono。
// Return a Mono that contains a "foo" value
Mono<String> fooMono() {
return Mono.just("foo");
}
And exactly as we did for the flux, we can propagate exceptions.
正如我們對(duì)Flux所做的那樣,我們可以傳播異常。
// Create a Mono that emits an IllegalStateException
Mono<String> errorMono() {
return Mono.error(new IllegalStateException());
}