如何在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接口?的详细内容,更多请关注其它相关文章!