我打算使用Scala Mongo Driver获取与Mongo标准匹配的所有记录。
使用Observable,您可以通过创建订阅来访问流:
val MaxBuffer: Long = 100
var docs: Queue[Document] = Queue.empty
var sub: Option[Subscription] = None
val q: Observable[Document]
def fetchMoreRecords: Unit = sub.get.request(MaxBuffer)
q.subscribe(new Observer[Document] {
override def onSubscribe(subscription: Subscription): Unit = {
sub = Some(subscription)
fetchMoreRecords
}
override def onError(e: Throwable): Unit = fail(out, e)
override def onComplete(): Unit = {
println("Stream is complete")
complete(out)
}
override def onNext(result: Document): Unit = {
if (doc.size == maxBuffer) {
fail(out, new RuntimeException("Buffer overflow"))
} else {
docs = docs :+ result
}
}
})
(此代码不完整)
我需要一个像:
这样的功能def isReady: Future[Boolean] = {}
每当onNext
被调用至少一次时,这就完成了。
做到这一点的坏方法是:
def isReady: Future[Boolean] = {
Future {
def wait: Unit = {
if (docs.nonEmpty) {
true
} else { wait }
}
wait
}
}
实现这一目标的最佳方式是什么?
答案 0 :(得分:0)
您想使用Promise
:
val promise = Promise[Boolean]()
...
override def onNext() = {
...
promise.tryComplete(Success(true))
}
override def onError(e: Throwable) =
promise.tryComplete(Failure(e))
val future = promise.future
当没有结果时,你应该做点什么来处理这个案子(就像现在一样,未来永远不会满足......