#1732: Moved splitter and aggregator from Alpakka Docs to Cookbook and … (#31203)

This commit is contained in:
Anthony Cheng 2022-03-10 10:23:55 +00:00 committed by GitHub
parent 1b14e25f82
commit 981eb17f2b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 190 additions and 1 deletions

View file

@ -0,0 +1,80 @@
/*
* Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
*/
package jdocs.stream.javadsl.cookbook;
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
import akka.testkit.javadsl.TestKit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
public class RecipeSplitter {
private static ActorSystem system;
@Test
public void simpleSplit() throws ExecutionException, InterruptedException {
// #Simple-Split
// Sample Source
Source<String, NotUsed> source = Source.from(Arrays.asList("1-2-3", "2-3", "3-4"));
CompletionStage<List<Integer>> ret =
source
.map(s -> Arrays.asList(s.split("-")))
.mapConcat(f -> f)
// Sub-streams logic
.map(s -> Integer.valueOf(s))
.runWith(Sink.seq(), system);
// Verify results
List<Integer> list = ret.toCompletableFuture().get();
assert list.equals(Arrays.asList(1, 2, 3, 2, 3, 3, 4));
// #Simple-Split
}
@Test
public void splitAggregate() throws ExecutionException, InterruptedException {
// #Aggregate-Split
// Sample Source
Source<String, NotUsed> source = Source.from(Arrays.asList("1-2-3", "2-3", "3-4"));
CompletionStage<List<Integer>> ret =
source
.map(s -> Arrays.asList(s.split("-")))
// split all messages into sub-streams
.splitWhen(a -> true)
// now split each collection
.mapConcat(f -> f)
// Sub-streams logic
.map(s -> Integer.valueOf(s))
// aggregate each sub-stream
.reduce((a, b) -> a + b)
// and merge back the result into the original stream
.mergeSubstreams()
.runWith(Sink.seq(), system);
// Verify results
List<Integer> list = ret.toCompletableFuture().get();
assert list.equals(Arrays.asList(6, 5, 7));
// #Aggregate-Split
}
@BeforeClass
public static void setup() throws Exception {
system = ActorSystem.create();
}
@AfterClass
public static void teardown() throws Exception {
TestKit.shutdownActorSystem(system);
}
}