简体   繁体   English

在Scala中将AsyncStream [A]强制为Seq [A]

[英]Forcing an AsyncStream[A] into a Seq[A] in scala

I am specifically using twitter's AsyncStream and I need to take the results of concurrent processing, and make it into a Seq, but the only way I've managed to get working is horrendous. 我专门使用Twitter的AsyncStream,我需要获取并发处理的结果并将其放入Seq中,但是我设法上班的唯一方法太可怕了。 This feels like it should be a one liner, but all my attempts with Await and force have either hung or not processed the work. 感觉应该像是一条直线,但我在Await和force中所做的所有尝试都已挂起或未处理。

Here's what I have working - what's a more idiomatic way of doing this? 这是我的工作-做这件事的更惯用的方法是什么?

  def processWork(work: AsyncStream[Work]): Seq[Result] = {
    // TODO: make less stupid
    val resultStream = work.flatMap { processWork }
    var results : Seq[Result] = Nil
    resultStream.foreach {
      result => {
        results = results :+ result
      }
    }
    results
  }

Like @MattFowler pointed out - you can force the stream and wait until it's complete using: 就像@MattFowler指出的那样-您可以使用以下命令强制流并等待其完成:

Await.result(resultStream.toSeq, 1.second)

toSeq will start realizing the stream and return a Future[Seq[A]] that completes once all the element are resolved, as documentated here . toSeq将开始实现流,并返回一个Future[Seq[A]] ,一旦解析了所有元素,该Future[Seq[A]]将完成,如此处所述

You can then block until the future completes by using Await.result . 然后,可以使用Await.result阻止直到将来完成。

Make sure your stream is finite! 确保您的流是有限的! Calling Await.result(resultStream.toSeq, 1.second) would hang forever. 调用Await.result(resultStream.toSeq, 1.second)将永远挂起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM