【发布时间】:2020-02-06 22:01:37
【问题描述】:
在 akka 中,我想将元素放入流中并返回一个对象。我知道这些元素可能是运行图表的来源。但是我怎样才能在运行时放置元素并返回一个对象呢?
import akka.actor.ActorSystem
import akka.stream.QueueOfferResult.{Dropped, Enqueued, Failure, QueueClosed}
import akka.stream.{ActorMaterializer, OverflowStrategy}
import akka.stream.scaladsl.{Keep, Sink, Source}
import scala.Array.range
import scala.util.Success
object StreamElement {
implicit val system = ActorSystem("StreamElement")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
def main(args: Array[String]): Unit = {
val (queue, value) = Source
.queue[Int](10, OverflowStrategy.backpressure)
.map(x => {
x * x
})
.toMat(Sink.asPublisher(false))(Keep.both)
.run()
range(0, 10)
.map(x => {
queue.offer(x).onComplete {
case Success(Enqueued) => {
}
case Success(Dropped) => {}
case _ => {
println("others")
}
}
})
}
}
我怎样才能得到返回的值?
【问题讨论】:
-
我很好奇你为什么要使用 Scala 集合而不是 Source 来提供 Stream 元素。特别是,由于您已经编写了一个 Stream,其中包含要在 Source Queue 和发布者 Sink 中捕获的物化值,我认为一个很好的用例是将 Scala 集合包装在 Source 中并创建一个订阅者 Source 来收集想要的值。
-
谢谢。你的意思是“.runWith(Sink.actorRefWithAck)”?
-
其实我对 Akka-stream 很陌生。对于我的情况,请您也举个例子吗?谢谢。
-
很难将示例代码显示为 cmets。请在下面查看我的答案。
标签: scala akka akka-stream