Docs: Reduce operator (#29641)

Co-authored-by: Arnout Engelen <github@bzzt.net>
This commit is contained in:
Muskan Gupta 2020-09-22 18:58:35 +05:30 committed by GitHub
parent 4d00f9a8e8
commit a12867b8b1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 1 deletions

View file

@ -15,6 +15,18 @@ Start with first element and then apply the current and next value to the given
Start with first element and then apply the current and next value to the given function, when upstream
complete the current value is emitted downstream. Similar to `fold`.
## Example
`reduce` will take a function and apply it on the incoming elements in the Stream and only emits its result when upstream completes.
Here, it will add the incoming elements.
Scala
: @@snip [Reduce.scala](/akka-docs/src/test/scala/docs/stream/operators/sourceorflow/Reduce.scala) { #reduceExample }
Java
: @@snip [SourceOrFlow.java](/akka-docs/src/test/java/jdocs/stream/operators/SourceOrFlow.java) { #reduceExample }
## Reactive Streams semantics
@@@div { .callout }
@ -26,4 +38,3 @@ complete the current value is emitted downstream. Similar to `fold`.
**completes** when upstream completes
@@@

View file

@ -456,6 +456,15 @@ class SourceOrFlow {
// #dropWhile
}
static void reduceExample() {
// #reduceExample
Source<Integer, NotUsed> source = Source.range(1, 100).reduce((acc, element) -> acc + element);
CompletionStage<Integer> result = source.runWith(Sink.head(), system);
result.thenAccept(System.out::println);
// 5050
// #reduceExample
}
void watchExample() {
// #watch
final ActorRef ref = someActor();

View file

@ -0,0 +1,23 @@
/*
* Copyright (C) 2009-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 Reduce {
implicit val system: ActorSystem = ???
implicit val ec: ExecutionContextExecutor = system.dispatcher
def reduceExample: Future[Unit] = {
//#reduceExample
val source = Source(1 to 100).reduce((acc, element) => acc + element)
val result: Future[Int] = source.runWith(Sink.head)
result.map(println)
//5050
//#reduceExample
}
}