如何用 Java 9 实现 Flow.Publisher 接口?
发布者接口是一个无界序列元素的提供程序,根据其订阅者的需求发布元素。响应调用Publisher.subscribe(Subscriber),订阅者上方法的可能调用顺序。这意味着onSubscribe()方法,后面是无界数量的onNext()方法(根据订阅者要求),再后面是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
广告