Play Framework 的 iteratee 库定义了一个方法,该方法Enumerator.fromCallback
允许基于 Future 的结果生成元素:
http://www.playframework.com/documentation/2.2.x/Enumerators
def fromCallback[E](
retriever: () => Future[Option[E]],
onComplete: () => Unit = () => (),
onError: (String, Input[E]) => Unit = (_: String, _: Input[E]) => ()
): Enumerator[E]
你可以在这里看到一个很好的例子,它被用来从 Web 服务传递分页结果:
http://engineering.klout.com/2013/01/iteratees-in-big-data-at-klout/
def pagingEnumerator(url:String):Enumerator[JsValue]={
var maybeNextUrl = Some(url) //Next url to fetch
Enumerator.fromCallback[JsValue] ( retriever = {
val maybeResponsePromise =
maybeNextUrl map { nextUrl=>
WS.url(nextUrl).get.map { reponse =>
val json = response.json
maybeNextUrl = (json \ "next_url").asOpt[String]
val code = response.status //Potential error handling here
json
}
}
/* maybeResponsePromise will be an Option[Promise[JsValue]].
* Need to 'flip' it, to make it a Promise[Option[JsValue]] to
* conform to the fromCallback constraints */
maybeResponsePromise match {
case Some(responsePromise) => responsePromise map Some.apply
case None => PlayPromise pure None
}
})
}
执行相同操作的等效 scalaz-stream 代码是什么?我很确定它可以使用Process.emit
orProcess.await
或可能来完成Process.eval
,但我很想看到一个成功的例子。这可能还需要将 scala Future 提升为 scalaz Task,这里有一个答案:
将 scala 2.10 未来转换为 scalaz.concurrent.Future // 任务
如果它使事情变得更简单,我们可以忽略 scala Future vs scalaz Task 位并假设我们有一个 Task。