Search code examples
scalaakkaakka-stream

scala-akka-streams difference between run() and runWIth()


What are the key difference between run and runWith:-

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Keep, Sink, Source}

object RunAndRunWith extends App {

  implicit val system: ActorSystem = ActorSystem("Run_RunWith")
  implicit val materializer: ActorMaterializer = ActorMaterializer()

  Source(1 to 10).toMat(Sink.foreach[Int](println))(Keep.right).run()
  Source(1 to 10).runWith(Sink.foreach[Int](println))

}

How to know which one to use?


Solution

  • to(Sink) and toMat(Sink) terminates the source with the sink and produces a RunnableGraph, which you can execute with run() but it also gives you the chance to set stream attributes for the whole graph before running it, or hand it to some other function/method which will run it (or possibly do something else with it than executing it).

    This form also gives you some control of where the materialized value should come from if you need that.

    Since wanting to terminate and run a source with a sink, without any additional attributes, keeping the materialized value of the sink, is so common, runWith(Sink) is a convenient shortcut for this.