Doc example for Sink.head (#28782)

This commit is contained in:
B YI 2020-03-23 21:03:09 +08:00 committed by GitHub
parent 2cccfa3c29
commit 1545f3fb25
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 0 deletions

View file

@ -17,6 +17,14 @@ Materializes into a @scala[`Future`] @java[`CompletionStage`] which completes wi
Materializes into a @scala[`Future`] @java[`CompletionStage`] which completes with the first value arriving, Materializes into a @scala[`Future`] @java[`CompletionStage`] which completes with the first value arriving,
after this the stream is canceled. If no element is emitted, the @scala[`Future`] @java[`CompletionStage`] is failed. after this the stream is canceled. If no element is emitted, the @scala[`Future`] @java[`CompletionStage`] is failed.
## Example
Scala
: @@snip [HeadSinkSpec.scala](/akka-stream-tests/src/test/scala/akka/stream/scaladsl/HeadSinkSpec.scala) { #head-operator-example }
Java
: @@snip [SinkDocExamples.java](/akka-docs/src/test/java/jdocs/stream/operators/SinkDocExamples.java) { #head-operator-example }
## Reactive Streams semantics ## Reactive Streams semantics
@@@div { .callout } @@@div { .callout }

View file

@ -78,6 +78,15 @@ public class SinkDocExamples {
// #takeLast-operator-example // #takeLast-operator-example
} }
static void headExample() {
// #head-operator-example
Source<Integer, NotUsed> source = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
CompletionStage<Integer> result = source.runWith(Sink.head(), system);
result.thenAccept(System.out::println);
// 1
// #head-operator-example
}
static void lastExample() { static void lastExample() {
// #last-operator-example // #last-operator-example
Source<Integer, NotUsed> source = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); Source<Integer, NotUsed> source = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

View file

@ -19,6 +19,17 @@ class HeadSinkSpec extends StreamSpec("""
"A Flow with Sink.head" must { "A Flow with Sink.head" must {
"yield the first value for simple source" in {
implicit val ec = system.dispatcher
//#head-operator-example
val source = Source(1 to 10)
val result: Future[Int] = source.runWith(Sink.head)
result.map(println)
// 1
//#head-operator-example
result.futureValue shouldEqual 1
}
"yield the first value" in assertAllStagesStopped { "yield the first value" in assertAllStagesStopped {
val p = TestPublisher.manualProbe[Int]() val p = TestPublisher.manualProbe[Int]()
val f: Future[Int] = Source.fromPublisher(p).map(identity).runWith(Sink.head) val f: Future[Int] = Source.fromPublisher(p).map(identity).runWith(Sink.head)