Operators: Add example for groupBy (#29875)

This commit is contained in:
Matteo Di Pirro 2020-12-09 17:44:04 +01:00 committed by GitHub
parent 4785ed1b48
commit 374d55cd34
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 0 deletions

View file

@ -28,6 +28,14 @@ memory issues. Elements belonging to those keys are drained directly and not sen
@@@
## Example
Scala
: @@snip [GroupBy.scala](/akka-docs/src/test/scala/docs/stream/operators/sourceorflow/GroupBy.scala) { #groupBy }
Java
: @@snip [GroupBy.java](/akka-docs/src/test/java/jdocs/stream/operators/SourceOrFlow.java) { #groupBy }
## Reactive Streams semantics
@@@div { .callout }

View file

@ -477,6 +477,18 @@ class SourceOrFlow {
// #watch
}
void groupByExample() {
// #groupBy
Source.range(1, 10)
.groupBy(2, i -> i % 2 == 0) // create two sub-streams with odd and even numbers
.reduce(Integer::sum) // for each sub-stream, sum its elements
.mergeSubstreams() // merge back into a stream
.runForeach(System.out::println, system);
// 25
// 30
// #groupBy
}
static CompletionStage<Done> completionTimeoutExample() {
// #completionTimeout
Source<Integer, NotUsed> source = Source.range(1, 100000).map(number -> number * number);

View file

@ -0,0 +1,25 @@
/*
* Copyright (C) 2020 Lightbend Inc. <https://www.lightbend.com>
*/
package docs.stream.operators.sourceorflow
import akka.actor.ActorSystem
import akka.stream.scaladsl.Source
object GroupBy {
def groupBySourceExample(): Unit = {
implicit val system: ActorSystem = ???
//#groupBy
Source(1 to 10)
.groupBy(maxSubstreams = 2, _ % 2 == 0) // create two sub-streams with odd and even numbers
.reduce(_ + _) // for each sub-stream, sum its elements
.mergeSubstreams // merge back into a stream
.runForeach(println)
//25
//30
//#groupBy
}
}