MongoDB scala driver: what's the best way to bring the future back with Observer callbacks?

I am writing a simple blog on the Play Framework and MongoDB using the Scala driver. So it works, and I'm happy, but I feel that my code is not good enough. Could you guys consider the following snippet, which is one of my mongo maintenance methods, and tell me if there is a way to make it cleaner:

def findByTitle(title:String)(implicit ec:ExecutionContext):Future[Option[Document]] = { val collection = db.getCollection("items") val results = collection.find(equal("title", title)) val contentPromise: Promise[Option[Document]] = Promise() results.subscribe(new Observer[scala.Document] { var empty: Boolean = true override def onError(e: Throwable): Unit = println("Error") override def onComplete(): Unit = { if (empty) contentPromise.success(None) } override def onNext(result: scala.Document): Unit = { empty = false contentPromise.success(Some(result)) } }) contentPromise.future } 

I decided to return Future[Option[Document]] , as there may be a chance that there is nothing provided by the name. Since the only way to work with Observable is through Observer callbacks, I need to declare Promise and then fulfill this promise in the onComplete() callback. To handle the case where there is no document on the provided title, I have no choice but to declare this variable var empty: Boolean = true , and then use it in onNext() and onComplete() callbacks.

Question: Is there a better way to approach this without using var inside my Observer instance?

+6
source share
1 answer

I think it is much easier to work with Future[T] instead of the observable:

 import org.mongodb.scala.ObservableImplicits._ def findByTitle(title: String)(implicit ec: ExecutionContext): Future[Option[Document]] = { val collection = db.getCollection("it") collection.find(equal("title", title)) .toFuture() .recoverWith { case e: Throwable => { Log(e); Future.failed(e) } } .map(_.headOption) } 

T in the future is actually Seq[T] . Thus, a simple check can eliminate the need for a mutable state.

+11
source

All Articles