Sink.foreach

Invoke a given procedure for each element received.

Sink operators

Signature

Sink.foreachSink.foreach

Description

Invoke a given procedure for each element received. Note that it is not safe to mutate shared state from the procedure.

The sink materializes into a Future[Done] CompletionStage<Done> which completes when the stream completes, or fails if the stream fails.

Note that it is not safe to mutate state from the procedure.

See also:

  • foreachAsync Invoke a given procedure asynchronously for each element received.
  • actorRef Send the elements from the stream to an ActorRef.

Example

This prints out every element to standard out.

Scala
sourceval printlnSink: Sink[Any, Future[Done]] = Sink.foreach(println)
val f = Source(1 to 4).runWith(printlnSink)
val done = Await.result(f, 100.millis)
// will print
// 1
// 2
// 3
// 4
Java
sourceSink<Integer, CompletionStage<Done>> printlnSink = Sink.foreach(System.out::println);
CompletionStage<Done> cs = Source.from(Arrays.asList(1, 2, 3, 4)).runWith(printlnSink, system);
Done done = cs.toCompletableFuture().get(100, TimeUnit.MILLISECONDS);
// will print
// 1
// 2
// 3
// 4

Reactive Streams semantics

cancels never

backpressures when the previous procedure invocation has not yet completed