一個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中文網其他相關文章!