如何动态地向Source添加元素?

kry*_*nio 23 scala akka akka-stream

我有示例代码生成一个未绑定的源并使用它:

对象Main {

 def main(args : Array[String]): Unit = {

  implicit val system = ActorSystem("Sys")
  import system.dispatcher

  implicit val materializer = ActorFlowMaterializer()

  val source: Source[String] = Source(() => {
     Iterator.continually({ "message:" + ThreadLocalRandom.current().nextInt(10000)})
    })

  source.runForeach((item:String) => { println(item) })
  .onComplete{ _ => system.shutdown() }
 }
Run Code Online (Sandbox Code Playgroud)

}

我想创建实现的类:

trait MySources {
    def addToSource(item: String)
    def getSource() : Source[String]
}
Run Code Online (Sandbox Code Playgroud)

我需要使用多个线程,例如:

class MyThread(mySources: MySources) extends Thread {
  override def run(): Unit = {
    for(i <- 1 to 1000000) { // here will be infinite loop
        mySources.addToSource(i.toString)
    }
  }
} 
Run Code Online (Sandbox Code Playgroud)

并预期完整代码:

object Main {
  def main(args : Array[String]): Unit = {
    implicit val system = ActorSystem("Sys")
    import system.dispatcher

    implicit val materializer = ActorFlowMaterializer()

    val sources = new MySourcesImplementation()

    for(i <- 1 to 100) {
      (new MyThread(sources)).start()
    }

    val source = sources.getSource()

    source.runForeach((item:String) => { println(item) })
    .onComplete{ _ => system.shutdown() }
  }
}
Run Code Online (Sandbox Code Playgroud)

如何实施MySources

cmb*_*ter 20

拥有非有限源的一种方法是使用特殊类型的actor作为源,混合在ActorPublisher特征中.如果你创建了这些类型的actor中的一个,然后通过调用包装ActorPublisher.apply,最终得到一个Reactive Streams Publisher实例,那么你可以使用applyfrom Source来从中生成一个Source.之后,您只需确保您的ActorPublisher类正确处理Reactive Streams协议,以便向下游发送元素,您就可以开始使用了.一个非常简单的例子如下:

import akka.actor._
import akka.stream.actor._
import akka.stream.ActorFlowMaterializer
import akka.stream.scaladsl._

object DynamicSourceExample extends App{

  implicit val system = ActorSystem("test")
  implicit val materializer = ActorFlowMaterializer()

  val actorRef = system.actorOf(Props[ActorBasedSource])
  val pub = ActorPublisher[Int](actorRef)

  Source(pub).
    map(_ * 2).
    runWith(Sink.foreach(println))

  for(i <- 1 until 20){
    actorRef ! i.toString
    Thread.sleep(1000)
  }

}

class ActorBasedSource extends Actor with ActorPublisher[Int]{
  import ActorPublisherMessage._
  var items:List[Int] = List.empty

  def receive = {
    case s:String =>
      if (totalDemand == 0) 
        items = items :+ s.toInt
      else
        onNext(s.toInt)    

    case Request(demand) =>  
      if (demand > items.size){
        items foreach (onNext)
        items = List.empty
      }
      else{
        val (send, keep) = items.splitAt(demand.toInt)
        items = keep
        send foreach (onNext)
      }


    case other =>
      println(s"got other $other")
  }


}
Run Code Online (Sandbox Code Playgroud)