Reactive - 03 - Mono

翻譯自: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個元素:Mono要么有值(帶元素完成),要么為空(無元素完成),要么為失敗(錯誤)。

A Mono<Void> can be used in cases where only the completion signal is interesting
(the Reactive Streams equivalent of a Runnable task completing).

在只對完成信號感興趣的情況下(相當(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)算符定義異步管道,該管道將針對每個訂閱重新具體化。

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

請注意,一些更改序列基數(shù)的API將返回Flux(反之亦然,在Flux中將基數(shù)減少到1的API將返回Mono)。
03_Mono.png

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)工廠返回一個空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)建一個從不發(fā)射任何東西的Mono。與empty()不同,它甚至不會發(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.

正如我們對Flux所做的那樣,我們可以傳播異常。
    // Create a Mono that emits an IllegalStateException
    Mono<String> errorMono() {
        return Mono.error(new IllegalStateException());
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容