Adding example of headOption operator (#29717)

Co-authored-by: Johan Andrén <johan@markatta.com>
This commit is contained in:
Muskan Gupta 2020-10-12 12:57:46 +05:30 committed by GitHub
parent fb1c6ff253
commit 1ff619259f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 42 additions and 0 deletions

View file

@ -14,6 +14,16 @@ Materializes into a @scala[`Future[Option[T]]`] @java[`CompletionStage<Optional<
Materializes into a @scala[`Future[Option[T]]`] @java[`CompletionStage<Optional<T>>`] which completes with the first value arriving wrapped in @scala[`Some`] @java[`Optional`],
or @scala[a `None`] @java[an empty Optional] if the stream completes without any elements emitted.
## Example
In this example there is an empty source i.e. it does not emit any element and to handle it we have used headOption operator which will complete with None.
Scala
: @@snip [HeadOption.scala](/akka-docs/src/test/scala/docs/stream/operators/sink/HeadOption.scala) { #headoption }
Java
: @@snip [SinkDocExamples.java](/akka-docs/src/test/java/jdocs/stream/operators/SinkDocExamples.java) { #headoption }
## Reactive Streams semantics
@@@div { .callout }

View file

@ -114,6 +114,15 @@ public class SinkDocExamples {
// #fold
}
static void headOptionExample() {
// #headoption
Source<Integer, NotUsed> source = Source.empty();
CompletionStage<Optional<Integer>> result = source.runWith(Sink.headOption(), system);
result.thenAccept(System.out::println);
// Optional.empty
// #headoption
}
static void ignoreExample() {
// #ignore
Source<String, NotUsed> lines = readLinesFromFile();

View file

@ -0,0 +1,23 @@
/*
* Copyright (C) 2020 Lightbend Inc. <https://www.lightbend.com>
*/
package docs.stream.operators.sink
import akka.actor.ActorSystem
import akka.stream.scaladsl.{ Sink, Source }
import scala.concurrent.{ ExecutionContextExecutor, Future }
object HeadOption {
implicit val system: ActorSystem = ???
implicit val ec: ExecutionContextExecutor = system.dispatcher
def headOptionExample(): Unit = {
//#headoption
val source = Source.empty
val result: Future[Option[Int]] = source.runWith(Sink.headOption)
result.foreach(println)
//None
//#headoption
}
}