我很难理解 NotUsed
的目的和意义和 Done
在 Akka Streams 中。
让我们看下面两个简单的例子:
使用未使用:
implicit val system = ActorSystem("akka-streams")
implicit val materializer = ActorMaterializer()
val myStream: RunnableGraph[NotUsed] =
Source.single("stackoverflow")
.map(s => s.toUpperCase())
.to(Sink.foreach(println))
val runResult:NotUsed = myStream.run()
使用完成
implicit val system = ActorSystem("akka-streams")
implicit val materializer = ActorMaterializer()
val myStream: RunnableGraph[Future[Done]] =
Source.single("stackoverflow")
.map(s => s.toUpperCase())
.toMat(Sink.foreach(println))(Keep.right)
val runResult: Future[Done] = myStream.run()
当我运行这些示例时,我在两种情况下都得到相同的输出:
STACKOVERFLOW //output
那么 NotUsed 和 Done 到底是什么?有什么区别,我什么时候应该更喜欢一个?
最佳答案
首先,你的选择是在NotUsed
之间和 Future[Done]
(不仅仅是 Done
)。
现在,您基本上决定了 物化值通过使用不同的组合器( to
和 toMat
和 Keep.right
),您的图表。
物化值是一种在流运行时与流交互的方式。此选择不会影响您的流处理的数据,因此您会在两种情况下看到相同的输出。相同的元素(字符串“stackoverflow”)通过两个流。
选择取决于您的主程序在运行流后应该做什么:
NotUsed
是正确的选择。它只是一个虚拟对象,它传达了不允许也不需要与流交互的信息Future[Done]
.通过这种方式,您可以使用(例如)onComplete
为其附加回调。或 map
. 关于scala - 了解 NotUsed 和 Done,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46915579/