[英]Scala Mongo driver getting results using Future
I am intending to fetch all records that match a criteria from Mongo using Scala Mongo Driver . 我打算使用Scala Mongo Driver从Mongo提取所有符合条件的记录。
Using Observables, you can access the stream by creating a subscription: 使用Observables,可以通过创建订阅来访问流:
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
}
}
})
(this code is incomplete) (此代码不完整)
I would need a function like: 我需要一个类似的功能:
def isReady: Future[Boolean] = {}
Which completes whenever onNext
was called at least once. 只要
onNext
至少被调用一次, onNext
完成。 The bad way to do this would be: 这样做的坏方法是:
def isReady: Future[Boolean] = {
Future {
def wait: Unit = {
if (docs.nonEmpty) {
true
} else { wait }
}
wait
}
}
What would be the best way to achieve this? 实现这一目标的最佳方法是什么?
You want to use Promise
: 您要使用
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
You should do something to handle the case when there are no result (as it is now, the future will never be satisfied ... 如果没有结果,您应该采取一些措施来处理这种情况(因为现在,未来将永远无法满足...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.