Maison  >  Article  >  Java  >  Comment implémenter l'interface Flow.Publisher dans Java 9 ?

Comment implémenter l'interface Flow.Publisher dans Java 9 ?

王林
王林avant
2023-08-30 17:57:06887parcourir

如何在Java 9中实现Flow.Publisher接口?

Une interface Publisher est un fournisseur qui fournit un nombre illimité d'éléments commandés à publier en fonction de la demande reçue de son(ses) Abonné(s). Séquence d'appel possible de méthodes sur Publisher.subscribe(Subscriber), en réponse à l'appel de Subscriber. Cela signifie la méthode onSubscribe(), suivie d'un nombre illimité de méthodes onNext() (comme requis par le Subscriber), puis soit la méthode onError() (en cas d'échec), soit la méthode onError() (en cas d'échec) Méthode onComplete() (quand plus aucun élément n'est disponible, tant que

Subscription

n'a pas été annulé).

Syntaxe

<strong>public interface Publisher<T> {
   public void subscribe(Subscriber<? super T><!--? super T--> s);
}</strong>

Exemple

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");
         }
      });
   }
}
Sortie🎜
<strong>item = [1]
item = [2]
item = [3]
item = [4]
item = [5]
item = [6]
item = [7]
item = [8]
item = [9]
item = [10]
complete</strong>
🎜

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer