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?
source share