阿卡限定集合
如果你不介意使用阿卡確定集合然後鍵入您可以使用grouped
函數:
//alternative stream formation
val stream = Source(1 to 100).via(Flow[Int].grouped(bufferSize))
.runWith(Sink foreach println)
用戶定義集合
如果你想控制緩衝區使用的集合類型,例如一個Seq
或Array
,那麼你可以用兩個Flow來執行這個操作。第一流執行scan
建立元素序列和第二流是恰到好處的大小順序的filter
(即「金髮姑娘」):
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Source, Flow, Sink}
object CollectFlowTest extends App {
implicit val as = ActorSystem()
implicit val mat = ActorMaterializer()
val bufferSize = 10
val buffer =
Flow[Int].scan[Seq[Int]](Seq.empty[Int]) {(seq, i) =>
if(seq.size < bufferSize)
seq :+ i
else
Seq(i)
}
val goldiLocks =
Flow[Seq[Int]].filter(_.size == bufferSize)
val stream = Source(1 to 100).via(buffer)
.via(goldiLocks)
.runWith(Sink foreach println)
implicit val ec = as.dispatcher
stream onComplete {_ => scala.util.Try(as.shutdown())}
}
然後,您可以添加你的「中級課程」 goldiLocks流後。
從2 Flow解決方案中的println表明,所產生的序列是所有尺寸正確的:
Seq(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Seq(11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
Seq(21, 22, 23, 24, 25, 26, 27, 28, 29, 30)
Seq(31, 32, 33, 34, 35, 36, 37, 38, 39, 40)
Seq(41, 42, 43, 44, 45, 46, 47, 48, 49, 50)
Seq(51, 52, 53, 54, 55, 56, 57, 58, 59, 60)
Seq(61, 62, 63, 64, 65, 66, 67, 68, 69, 70)
Seq(71, 72, 73, 74, 75, 76, 77, 78, 79, 80)
Seq(81, 82, 83, 84, 85, 86, 87, 88, 89, 90)
Seq(91, 92, 93, 94, 95, 96, 97, 98, 99, 100)
感謝這正是我一直在尋找 –
'流量[INT] .grouped(緩衝區大小)'更簡單。 – sschaef