甲出版商接口是测序元件的无限数量的提供商,根据从其所接收的需求发布它们订户(一个或多个)。响应于调用Publisher.subscribe(订户),用于在 方法的可能调用序列订户。这意味着onSubscribe()方法,然后是无限数量的onNext()方法(根据Subscriber的请求),然后是onError()方法(如果存在故障)或onComplete()方法(如果没有更多可用的元素)只要未取消订阅。
public interface Publisher<T> { public void subscribe(Subscriber<? super T> s); }
import java.util.concurrent.*; import java.util.*; import java.util.stream.*; class SimplePublisher implements Flow.Publisher<Integer> { private final Iterator<Integer> iterator; SimplePublisher(int count) { this.iterator = IntStream.rangeClosed(1, count).iterator(); } @Override public void subscribe(Flow.Subscriber<? super Integer> subscriber) { iterator.forEachRemaining(subscriber::onNext); subscriber.onComplete(); } } public class SimplePublisherImplTest { public static void main(String args[]) { new SimplePublisher(10).subscribe(new Flow.Subscriber<>() { @Override public void onSubscribe(Flow.Subscription subscription) { } @Override public void onNext(Integer item) { System.out.println("item = [" + item + "]"); } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { System.out.println("complete"); } }); } }
输出结果
item = [1] item = [2] item = [3] item = [4] item = [5] item = [6] item = [7] item = [8] item = [9] item = [10] complete