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
或Process.await
或Process.eval
来完成,但我很乐意看到一个成功的例子。这可能还需要将scala Future提升为scalaz任务,这里有一个答案:
Convert scala 2.10 future to scalaz.concurrent.Future // Task
如果它使事情变得更简单,我们可以忽略scala Future vs scalaz Task位并假设我们有一个Task。
答案 0 :(得分:2)
要从scala.concurrent.Future获取scalaz.concurrent.Task,您可以使用Task.async,当您手头有任务时,您可以这样做:
import java.util.concurrent.atomic.AtomicInteger
import scalaz.concurrent.Task
import scalaz.stream.Process.End
import scalaz.stream._
val cnt = new AtomicInteger(0)
val task: Task[String] = Task {
if (cnt.incrementAndGet() <= 10) s"Task ${cnt.get}" else throw End
}
Process.repeatEval(task).runLog.run.foreach(println)