Terminating a stream

Terminating a stream

Streams do not run on the caller thread, instead they run on a different background thread. This is done to avoid blocking the caller. Therefore, once the stream completes, you need to terminate the underlying actor system to completely end the program. In order to do that you can use the Future returned by runWith to terminate that actor system.

 implicit val system = ActorSystem()
 implicit val materializer = ActorMaterializer()
 implicit val ec = system.dispatcher
 
 val source = Source(0 to 10)
                       .map(n => n * 2)
                       .runWith(Sink.foreach(println)) // returns a Future[Done]
                       .onComplete(_ => system.terminate())  // onComplete callback of the future


Akka Stream API also has a watchForTermination method that can be used to monitor stream termination both for success and failure cases. This is usually a good place to add logging messages or trigger some follow-up actions.

 implicit val system = ActorSystem()
 implicit val materializer = ActorMaterializer()
 implicit val ec = system.dispatcher

 val source = Source(0 to 10)
                    .map(n => n * 2)
                    .watchTermination() {(_, done) =>
                        done.onComplete {
                            case Success(_) => println("Stream completed successfully")
                                system.terminate()
                            case Failure(error) => println(s"Stream failed with error ${error.getMessage}")
                                system.terminate()
                        }
                    }
                    .runWith(Sink.foreach(println))


See more in the Java or Scala documentation.


    • Related Articles

    • Error handling and recovery in Akka Streams

      When developing applications you should assume that there will be unexpected issues. For this, Akka provides a set of supervision strategies to deal with errors within your actors. Akka streams is no different, in fact its error handling strategies ...
    • How to implement batching logic in Akka Streams

      A common request we see with streaming data is the need to take the stream of elements and group them together (i.e. committing data to a database, a message queue or disk). Batching is usually a more efficient and performant solution than writing a ...
    • How to do Throttling in Akka Streams

      When building a streaming application you may find the need to throttle the upstream so as to avoid exceeding a specified rate. Akka Stream's provides the capability to either fail the stream or shape it by applying back pressure. This is simply done ...
    • How to do Rate Limiting in Akka Streams

      In certain scenarios it is important to limit the number of concurrent requests to other services. For example, to avoid overwhelming the services and avoid performance degradation, or to maintain service level agreements. This is particularly ...
    • How to stream multiple stream actions concurrently

      To construct efficient, scalable and low-latency data streams, it is often important to perform tasks concurrently. However Akka Streams executes stages sequentially on a single thread, so you must explicitly request this concurrency. Inserting these ...