我想创建自定义StatefulStage,它应该像groupBy
方法和发出Source[A, Unit]
元素一样工作,但我不明白如何创建实例Source[A, Unit]
并将传入元素推送到它。这是存根:
class GroupBy[A, Mat]() extends StatefulStage[A, Source[A, Unit]] {
override def initial: StageState[A, Source[A, Unit]] = new StageState[A, Source[A, Unit]] {
override def onPush(elem: A, ctx: Context[Source[A, Unit]]): SyncDirective = {
val source: Source[A, Unit] = ... // Need to create source here
// and push `elem` to `source` here
emit(List(source).iterator, ctx)
}
}
}
您可以将以下代码段用于测试 GroupBy 流(它应该从创建的流中打印事件):
case class Tick()
case class Event(timestamp: Long, sessionUid: String, traffic: Int)
implicit val system = ActorSystem()
import system.dispatcher
implicit val materializer = ActorMaterializer()
var rnd = Random
rnd.setSeed(1)
val eventsSource = Source
.tick(FiniteDuration(0, SECONDS), FiniteDuration(1, SECONDS), () => Tick)
.map {
case _ => Event(System.currentTimeMillis / 1000, s"session-${rnd.nextInt(5)}", rnd.nextInt(10) * 10)
}
val flow = Flow[Event]
.transform(() => new GroupByUntil)
.map {
(source) => source.runForeach(println)
}
eventsSource
.via(flow)
.runWith(Sink.ignore)
.onComplete(_ => system.shutdown())
谁能解释我该怎么做?
更新:
我根据这个答案编写了以下onPush
方法,但它没有打印事件。据我了解,只有当它作为流的一部分运行但我想在测试片段之外运行流时,我才能将元素推送到源。如果我像本例中那样运行流程,那么它将处理事件并将它们发送到. 我认为这是我的测试片段没有打印事件的原因。GroupBy
GroupBy
Sink.ignore
override def onPush(elem: A, ctx: Context[Source[A, Unit]]): SyncDirective = {
val source: Source[A, ActorRef] = Source.actorRef[A](1000, OverflowStrategy.fail)
val flow = Flow[A].to(Sink.ignore).runWith(source)
flow ! elem
emit(List(source.asInstanceOf[Source[A, Unit]]).iterator, ctx)
}
那么,如何解决呢?