在Java 9中,我们如何实现Subscriber接口?

在Java 9中,我们如何实现Subscriber接口?

Java 9 通过引入一些接口来支持创建反应式流PublisherSubscriberSubscription和实现Publisher 接口的SubmissionPublisher 类。每个接口可以根据反应式流的原则扮演不同的角色。

我们可以使用Subscriber 接口订阅由publisher发布的数据。我们需要实现Subscriber 接口并为抽象方法提供实现。

Flow.Subscriber接口的方法:

  • onComplete():当Publisher对象完成其角色时调用此方法。
  • onError():当Publisher出现问题并通知Subscriber时调用此方法。
  • onNext():当Publisher有新信息要通知给所有Subscribers时调用此方法。
  • onSubscribe():当Publisher添加Subscriber时调用此方法。

示例

import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;
import java.util.stream.IntStream;

public class SubscriberImplTest {
   public static class Subscriber implements <strong>Flow.Subscriber<Integer></strong> {
      private <strong>Flow.Subscription</strong> subscription;
      private boolean isDone;
      
     <strong> @Override</strong>
      public void <strong>onSubscribe</strong>(Flow.Subscription subscription) {
         System.out.println("Subscribed");
         this.subscription = subscription;
         this.subscription.request(1);
      }
      <strong>@Override</strong>
      public void <strong>onNext</strong>(Integer item) {
         System.out.println("Processing " + item);
         this.subscription.request(1);
      }
      <strong>@Override</strong>
      public void <strong>onError</strong>(Throwable throwable) {
         throwable.printStackTrace();
      }
      <strong>@Override</strong>
      public void <strong>onComplete()</strong> {
         System.out.println("Processing done");
         isDone = true;
      }
   }
   public static void main(String args[]) throws InterruptedException {
      <strong>SubmissionPublisher<Integer></strong> publisher = new <strong>SubmissionPublisher<></strong><strong>()</strong>;
      <strong>Subscriber </strong>subscriber = new <strong>Subscriber()</strong>;
      publisher.subscribe(subscriber);
      <strong>IntStream</strong> intData = <strong>IntStream.rangeClosed</strong>(1, 10);
      intData.forEach(<strong>publisher::submit</strong>);
      publisher.<strong>close()</strong>;
      while(!subscriber.isDone) {
         Thread.sleep(10);
      }
      System.out.println("Done");
   }
}

输出

<strong>Subscribed
Processing 1
Processing 2
Processing 3
Processing 4
Processing 5
Processing 6
Processing 7
Processing 8
Processing 9
Processing 10
Processing done
Done</strong>

以上就是在Java 9中,我们如何实现Subscriber接口?的详细内容,更多请关注其它相关文章!