首頁 >Java >java教程 >如何在Java 9中實作Flow.Publisher介面?

如何在Java 9中實作Flow.Publisher介面?

王林
王林轉載
2023-08-30 17:57:06937瀏覽

如何在Java 9中实现Flow.Publisher接口?

一個Publisher介面是提供無限數量的有序元素的提供者,根據從其Subscriber(s)接收到的需求進行發布。回應呼叫Publisher.subscribe(Subscriber)Subscriber上的方法的可能呼叫順序。這意味著onSubscribe()方法,後面跟著無限數量的onNext()方法(根據Subscriber的要求),然後是onError()方法(如果有失敗)或onComplete()方法(當沒有更多元素可用時,只要Subscription未被取消)。

語法

<strong>public interface Publisher<T> {
   public void subscribe(Subscriber<? super T><!--? super T--> s);
}</strong>

範例

import java.util.concurrent.*;
import java.util.*;
import java.util.stream.*;

class SimplePublisher implements <strong>Flow.Publisher<Integer></strong> {
   private final <strong>Iterator<Integer></strong> iterator;
   SimplePublisher(int count) {
      this.iterator = <strong>IntStream</strong>.rangeClosed(1, count).iterator();
   }
   <strong>@Override</strong>
   public void <strong>subscribe</strong>(<strong>F</strong><strong>low.Subscriber<? super Integer></strong><!--? super Integer--> subscriber) {
      iterator.<strong>forEachRemaining</strong>(<strong>subscriber::onNext</strong>);
      subscriber.<strong>onComplete()</strong>;
   }
}

public class SimplePublisherImplTest {
   public static void main(String args[]) {
      new SimplePublisher(10).<strong>subscribe</strong>(new <strong>Flow.Subscriber<>()</strong> {
         <strong>@Override</strong>
         public void <strong>onSubscribe</strong>(<strong>Flow.Subscription</strong> subscription) {
         }
         <strong>@Override</strong>
         public void <strong>onNext</strong>(Integer item) {
            System.out.println("item = [" + item + "]");
         }
         <strong>@Override</strong>
         public void <strong>onError</strong>(Throwable throwable) {
         }
         <strong>@Override</strong>
         public void <strong>onComplete()</strong> {
            System.out.println("complete");
         }
      });
   }
}

輸出

<strong>item = [1]
item = [2]
item = [3]
item = [4]
item = [5]
item = [6]
item = [7]
item = [8]
item = [9]
item = [10]
complete</strong>

以上是如何在Java 9中實作Flow.Publisher介面?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除