我试图在akka流中的Keep
组合下创建以下示例:
import java.nio.file.Paths
import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.{ActorMaterializer, IOResult}
import akka.stream.scaladsl.{FileIO, Flow, Keep, Sink, Source}
import akka.util.ByteString
import scala.concurrent.Future
import scala.util.{Failure, Success}
object FileConsumer extends App {
implicit val system = ActorSystem("reactive-tweets")
implicit val materializer = ActorMaterializer()
val source: Source[Int, NotUsed] = Source(1 to 100)
val factorials = source.scan(BigInt(1))((acc, next) => acc * next)
val result: Future[IOResult] =
factorials.map(_.toString).runWith(lineSink("factorial2.txt"))
implicit val ec = system.dispatcher
result.onComplete {
case Success(v) => println(s"Fileinfo ${ v.count }")
case Failure(e) => println(e)
}
def lineSink(filename: String): Sink[String, Future[IOResult]] =
Flow[String].map(s => ByteString(s + "\n")).toMat(FileIO.toPath(Paths.get(filename)))(Keep.right)
}
得到的蓝图是
Sink[String, Future[IOResult]]
,这意味着它接受字符串作为其输入,当实现时,它将创建Future[IOResult]
类型的辅助信息(当在源或流上链接操作时,辅助信息的类型 - 称为“物化值” - 由最左边的起点给出;因为我们想要保留FileIO.toPath
接收器提供的东西,我们需要说Keep.right
)。
但是,当我想保持ByteString
在左侧时,我试过:
def lineSink2(filename: String): Sink[String, Future[ByteString]] =
Flow[String].map(s => ByteString(s + "\n")).toMat(Sink.foreach(println))(Keep.left)
但它根本不编译。
我也不明白:
由最左边的起点给出
最左边的起点是Flow
?
我想,我还不了解Keep
的想法。
Sink.foreach的定义如下:
def foreach[T](f: T ⇒ Unit): Sink[T, Future[Done]]
这意味着物化价值是未来[完成]
如果是流量,你有:
val value: Flow[String, ByteString, NotUsed] = Flow[String].map(s => ByteString(s + "\n"))
其物化价值是NotUsed
在这种情况下:
Keep.left - NotUsed - 来源或流量的物化价值
Keep.right - 未来[完成] - 沉没的水平价值
Keep.both - (NotUsed,Future [Done])
重要的事实是在很多情况下物化价值不是流经物流的元素的价值,而是相反