Reputation: 1367
What's the difference between akka.stream.scaladsl.Source.reduce() and runReduce() functions?
I checked here https://doc.akka.io/api/akka/current/akka/stream/scaladsl/Source.html and it's pretty clear that the reduce()
"folds" all the elements using the first element as a "basis". I don't quite understand what's an advantage of using runReduce()
for running this Source
with a reduce()
function. Why does it return a Future
?
Upvotes: 0
Views: 280
Reputation: 1940
You need 2 steps to execute an akka stream:
reduce does only step 1, and runReduce does steps 1 and 2.
import akka.actor.ActorSystem
import akka.stream.scaladsl._
import scala.util.{Failure, Success}
import scala.concurrent.ExecutionContext.Implicits.global
implicit val actorSystem = ActorSystem("example")
// reduce
Source(1 to 10).reduce(_ + _).runForeach(println).onComplete {
case Success(v) => println("done")
case Failure(e) => println(e.getMessage)
}
// it prints:
// 55
// done
// runReduce
Source(1 to 10).runReduce(_ + _).onComplete {
case Success(v) => println(v)
case Failure(e) => println(e.getMessage)
}
// it prints:
// 55
Feel free to try the example in playground https://scastie.scala-lang.org/2Iure8pDSUWcLjFVGflyUQ
Upvotes: 1