播放2.1:等待枚举者的结果

时间:2014-04-03 17:14:55

标签: scala playframework future

我正在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]。文档充其量令人困惑。

我该怎么做?

1 个答案:

答案 0 :(得分:-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 - >的更详细示例EnumeratorIteratee提供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") 链:

{{1}}