Add Sink.asPublisher example and update doc (#30105)

Co-authored-by: Renato Cavalcanti <renato@cavalcanti.be>
This commit is contained in:
Muskan Gupta 2021-05-13 00:46:41 +05:30 committed by GitHub
parent 240378f062
commit dd8b514e89
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 77 additions and 1 deletions

View file

@ -7,11 +7,13 @@ package jdocs.stream.operators;
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.stream.javadsl.AsPublisher;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
// #takeLast-operator-example
import akka.japi.Pair;
import org.reactivestreams.Publisher;
// #takeLast-operator-example
import java.util.*;
import java.util.concurrent.CompletableFuture;
@ -139,6 +141,26 @@ public class SinkDocExamples {
// #ignore
}
static void asPublisherExample() {
// #asPublisher
Source<Integer, NotUsed> source = Source.range(1, 5);
Publisher<Integer> publisherFalse =
source.runWith(Sink.asPublisher(AsPublisher.WITHOUT_FANOUT), system);
CompletionStage<Integer> resultFromFirstSubscriberFalse =
Source.fromPublisher(publisherFalse)
.runWith(Sink.fold(0, (acc, element) -> acc + element), system);
CompletionStage<Integer> resultFromSecondSubscriberFalse =
Source.fromPublisher(publisherFalse)
.runWith(Sink.fold(1, (acc, element) -> acc * element), system);
resultFromFirstSubscriberFalse.thenAccept(System.out::println); // 15
resultFromSecondSubscriberFalse.thenAccept(
System.out
::println); // No output, because the source was not able to subscribe to the publisher.
// #asPublisher
}
private static Source<String, NotUsed> readLinesFromFile() {
return Source.empty();
}