Home > Java > javaTutorial > What are the steps to implement Flow API in Java 9?

What are the steps to implement Flow API in Java 9?

PHPz
Release: 2023-08-25 21:13:13
forward
752 people have browsed it

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

Flow API corresponds to the Reactive Streams specification in Java 9, which is a de facto standard. It contains a minimal set of interfaces that capture the core of asynchronous publishing and subscription.

The following are the key interfaces of Flow API:

1) Flow.Publisher: It generates items for subscribers to consume, and it contains only one method: subscribe(Subscriber), whose purpose should be obvious.

Syntax

<strong>void subscribe(Flow.Subscriber<? super T><!--? super T--> subscriber)</strong>
Copy after login

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

<strong>void onSubscribe(Flow.Subscription subscription)
void onNext(T item)
void onError(Throwable throwable)
void onComplete()</strong>
Copy after login

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

<strong>void request(long n)
void cancel()</strong>
Copy after login

Flow API execution steps:

  • First, we need to create a Publisher and a Subscriber.
  • Use Publisher::subscribe to subscribe to Subscriber.
  • Publisher creates a Subscription and calls Subscriber::onSubscription so that Subscriber can store the subscription.
  • At a certain moment, Subscriber calls Subscription::request to request a certain number of items.
  • Publisher passes items to Subscriber by calling Subscriber::onNext. It will not publish more than the requested number of items.
  • Publisher may encounter a problem at some point and call Subscriber::onComplete or Subscriber::onError respectively.
  • Subscriber can request more items at intervals or disconnect by calling Subscription::cancel.

The above is the detailed content of What are the steps to implement Flow API in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template