简体   繁体   中英

Scala Mongo driver getting results using Future

I am intending to fetch all records that match a criteria from Mongo using Scala Mongo Driver .

Using Observables, you can access the stream by creating a subscription:

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. 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 :

 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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM