Akka Stream:无法写入文件接收器

Rax*_*ore 1 scala akka akka-stream

我试图运行一个简单的Akka流文件接收器示例但没有成功.我可以创建一个Source,运行Flow然后创建一个文件但ByteString没有写入文件.然而,如果我尝试将流输出打印到控制台,我可以这样做.我在这里错过了什么吗?

import akka.stream._ 
import akka.stream.scaladsl._
import akka.{ NotUsed, Done}
import akka.actor.ActorSystem
import akka.util.ByteString
import scala.concurrent._
import scala.concurrent.duration._
import java.nio.file.Paths

object First extends App {

  val source: Source[Int, NotUsed] = Source ( 1 to 100)

  implicit val system = ActorSystem("QuickStart")
  implicit val materializer = ActorMaterializer()

  // works: prints 1-100
  //source.runForeach(println) (materializer)

  val factorials = source.scan(BigInt(1))((acc,next) => acc * next)

  // there is no content in the Sink (file)
  /**val result =
    factorials
    .map(num => ByteString(s"${num}\n"))
    .runWith(FileIO.toPath(Paths.get("factorials.txt")))
**/

  def lineSink(fileName: String): Sink[String, Future[IOResult]] =
    Flow[String]
    .map(s => ByteString(s + "\n"))
    .toMat(FileIO.toPath(Paths.get(fileName))) (Keep.right)

  //There is no content in the Sink.
  factorials.map(_.toString).runWith(lineSink("factorials.txt"))

system.terminate()

}
Run Code Online (Sandbox Code Playgroud)

build.sbt有:

name := "akkaGuide"
    version := "1.0"
    scalaVersion := "2.11.8"
    libraryDependencies ++= Seq(
      "com.typesafe.akka" %% "akka-stream" % "2.4.10"
    )
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的时间.

Bri*_*ent 6

我想你可能只是太早终止了.尝试等到Future完成:

val result = factorials.map(_.toString).runWith(lineSink("factorials.txt"))
import system.dispatcher
result.onComplete { _ => system.terminate() }
Run Code Online (Sandbox Code Playgroud)