要播放Play响应,我想将Enumerator
传递给结果的feed
方法。我需要将一个状态从产生/消费迭代步骤传递到下一步(或保持状态)。这里
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 match {
case Some(responsePromise) => responsePromise map Some.apply
case None => PlayPromise pure None
}
})
}
您可以将状态添加到播放Enumerator
?这个例子是线程安全的吗?
(在上面的示例中使用了与Promise / Future相关的旧Play API;如果它不影响问题本身,我们就会忽略这个事实)
答案 0 :(得分:2)
您应该使用Enumerator.unfoldM
:
Enumerator.unfoldM(Some(firstURL)) { maybeNextUrl =>
maybeNextUrl map { nextUrl =>
WS.url(nextUrl).get.map { response =>
val json = response.json
val newUrl = (json \ "next_url").asOpt[String]
val code = response.status //Potential error handling here
Some((newUrl, json))
}
} getOrElse (Future.successful(None))
}