【问题标题】:Play 2.1: Await result from enumerator播放 2.1:等待枚举器的结果
【发布时间】:2014-04-04 06:42:53
【问题描述】:

我正在 Play Framework 2.1 中测试我的 WebSocket 代码。我的方法是获取用于实际 Web 套接字的迭代器/枚举器对,然后测试推入和拉出数据。

不幸的是,我只是不知道如何从枚举器中获取数据。现在我的代码大致是这样的:

val (in, out) = createClient(FakeRequest("GET", "/myendpoint"))

in.feed(Input.El("My input here"))
in.feed(Input.EOF)

//no idea how to get data from "out"

据我所知,从枚举器中获取数据的唯一方法是通过迭代器。但我不知道如何等到从枚举器中获得完整的字符串列表。我想要的是List[String],而不是Future[Iteratee[A,String]]Expectable[Iteratee[String]] 或另一个Iteratee[String]。文档充其量是令人困惑的。

我该怎么做?

【问题讨论】:

  • 你能添加createClient方法的(简化的)内容吗?

标签: scala playframework future


【解决方案1】:

您可以像这样使用Enumerator

  val out = Enumerator("one", "two")

  val consumer = Iteratee.getChunks[String]

  val appliedEnumeratorFuture = out.apply(consumer)

  val appliedEnumerator = Await.result(appliedEnumeratorFuture, 1.seconds)

  val result = Await.result(appliedEnumerator.run, 1.seconds)

  println(result) // List("one", "two")

请注意,您需要等待Future 两次,因为EnumeratorIteratee 分别控制生产和消费值的速度。

Iteratee -> Enumerator 链的更详细示例,其中提供 Iteratee 导致 Enumerator 产生值:

  // create an enumerator to which messages can be pushed
  // using a channel
  val (out, channel) = Concurrent.broadcast[String]

  // create the input stream. When it receives an string, it
  // will push the info into the channel
  val in =
    Iteratee.foreach[String] { s =>
      channel.push(s)
    }.map(_ => channel.eofAndEnd())

  // Instead of using the complex `feed` method, we just create
  // an enumerator that we can use to feed the input stream
  val producer = Enumerator("one", "two").andThen(Enumerator.eof)

  // Apply the input stream to the producer (feed the input stream)
  val producedElementsFuture = producer.apply(in)

  // Create a consumer for the output stream
  val consumer = Iteratee.getChunks[String]

  // Apply the consumer to the output stream (consume the output stream)
  val consumedOutputStreamFuture = out.apply(consumer)

  // Await the construction of the input stream chain
  Await.result(producedElementsFuture, 1.second)
  // Await the construction of the output stream chain
  val consumedOutputStream = Await.result(consumedOutputStreamFuture, 1.second)
  // Await consuming the output stream
  val result = Await.result(consumedOutputStream.run, 1.second)

  println(result) // List("one", "two")

【讨论】:

    猜你喜欢
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多