Evgeny Mamaev
Evgeny Mamaev

Reputation: 1367

Difference between reduce and runReduce in akka.stream.scaladsl.Source?

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

Answers (1)

yiksanchan
yiksanchan

Reputation: 1940

You need 2 steps to execute an akka stream:

  • Construct a blueprint
  • Run it (so-called materialize)

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

Related Questions