首页 > 文章列表 > 在Java 9中执行Flow API的步骤是什么?

在Java 9中执行Flow API的步骤是什么?

207 2023-09-03

Flow API在Java 9中对应于Reactive Streams 规范,这是一种事实上的标准。它包含了一组最小的接口,捕捉了异步发布和订阅的核心。

以下是Flow API的关键接口:

1) Flow.Publisher:它为订阅者生成要消费的项目,它只包含一个方法:subscribe(Subscriber),其目的应该是显而易见的。

Syntax

void subscribe(Flow.Subscriber<? super T> subscriber)

2) Flow.Subscriber: It subscribes to publishers (usually only one) to receive items (via method onNext(T)), error messages (onError(Throwable)), or a signal that no more items are to be expected (onComplete()). Before any of those things happen, the publisher calls onSubscription(Subscription) method.

Syntax

void onSubscribe(Flow.Subscription subscription)
void onNext(T item)
void onError(Throwable throwable)
void onComplete()

3) Flow.Subscription: The connection between a single publisher and a single subscriber. The subscriber can use it to request more items (request(long)) or break the connection (cancel()).

Syntax

void request(long n)
void cancel()

Flow API的执行步骤:

  • 首先,我们需要创建一个Publisher和一个Subscriber
  • 使用Publisher::subscribe订阅Subscriber。
  • Publisher创建一个Subscription并调用Subscriber::onSubscription,以便Subscriber可以存储订阅。
  • 在某个时刻,Subscriber调用Subscription::request来请求一定数量的项目。
  • Publisher通过调用Subscriber::onNext将项目传递给Subscriber。它不会发布超过请求的项目数量。
  • Publisher可能在某个时刻遇到问题并分别调用Subscriber::onComplete或Subscriber::onError。
  • Subscriber可以每隔一段时间请求更多项目,也可以通过调用Subscription::cancel来断开连接。