我们如何使用 Java 9 中的发布者-订阅者实现 Flow API?


Flow API(java.util.concurrent.Flow)已纳入 Java 9 中。它有助于了解发布者订阅者接口以执行预期操作的不同交互方式。

Flow API 包含可基于响应流规范的 发布者、订阅者、订阅处理器接口。

在以下示例中,我们可以使用发布者-订阅者接口实现 Flow API。

示例

import java.util.concurrent.Flow.Publisher;
import java.util.concurrent.Flow.Subscriber;
import java.util.concurrent.Flow.Subscription;

public class FlowAPITest {
   public static void main(String args[]) {
      Publisher<Integer> publisherSync = new Publisher<Integer>() {   // Create publisher
         @Override
         public void subscribe(Subscriber<? super Integer> subscriber) {
            for(int i = 0; i < 10; i++) {
               System.out.println(Thread.currentThread().getName() + " | Publishing = " + i);
               subscriber.onNext(i);
            }
            subscriber.onComplete();
         }
      };
      Subscriber<Integer> subscriberSync = new Subscriber<Integer>() {   // Create subscriber
         @Override
         public void onSubscribe(Subscription subscription) {
         }
         @Override
         public void onNext(Integer item) {
            System.out.println(Thread.currentThread().getName() + " | Received = " + item);
            try {
               Thread.sleep(100);
            } catch(InterruptedException e) {
               e.printStackTrace();
            }
         }
         @Override
         public void onError(Throwable throwable) {
         }
         @Override
         public void onComplete() {
         }
      };
      publisherSync.subscribe(subscriberSync);
   }
}

输出

main | Publishing = 0
main | Received = 0
main | Publishing = 1
main | Received = 1
main | Publishing = 2
main | Received = 2
main | Publishing = 3
main | Received = 3
main | Publishing = 4
main | Received = 4
main | Publishing = 5
main | Received = 5
main | Publishing = 6
main | Received = 6
main | Publishing = 7
main | Received = 7
main | Publishing = 8
main | Received = 8
main | Publishing = 9
main | Received = 9

更新于:2020 年 4 月 14 日

1K+ 浏览量

开启你的 职业生涯

完成课程获取认证

开始
广告
© . All rights reserved.