MongoDB scala驱动程序:在处理观察器回调时,返回Future的最佳方法是什么?
我正在写一篇关于Play Framework和使用Scala驱动程序的MongoDB的简单博客。 所以它工作了,我很高兴,但感觉我的代码不够好。 你们能回顾一下我的mongo服务方法之一的以下代码片段,并告诉我是否有办法让它更干净:MongoDB scala驱动程序:在处理观察器回调时,返回Future的最佳方法是什么?,mongodb,scala,playframework,Mongodb,Scala,Playframework,我正在写一篇关于Play Framework和使用Scala驱动程序的MongoDB的简单博客。 所以它工作了,我很高兴,但感觉我的代码不够好。 你们能回顾一下我的mongo服务方法之一的以下代码片段,并告诉我是否有办法让它更干净: def findByTitle(title:String)(implicit ec:ExecutionContext):Future[Option[Document]] = { val collection = db.getCollection("items
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
}
我决定返回Future[Option[Document]]
,因为标题可能没有提供任何内容。至于使用Observable
的唯一方法是通过Observable
回调,我需要声明一个Promise
,然后在onComplete()
回调中实现该承诺。要处理没有提供标题的文档的情况,我别无选择,只能将此var声明为空:Boolean=true
变量,然后在onNext()
和onComplete()
回调中使用它
问题:在我的
观察者
实例中没有使用var
的情况下,有没有更好的方法来实现这一点?我认为使用未来[T]
而不是可观察的:
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
实际上是一个Seq[T]
。这样,一个简单的检查就可以消除对可变状态的需要。或者为了正确起见,您可以使用它,尽管toFuture().map{seq=>if(seq.isEmpty)None-other-Some(seq.head)}
您可以将future的值模式匹配为选项[Try[T],但如果我没有弄错的话,就不是未来本身。我还将可能的错误记录添加到您的日志中code@YuvalItzchakov你能告诉我你是从哪里找到未来的toFuture
方法的吗?很棒的发现,我肯定没有发现:(看起来它可以在interwebz上使用更多指向它文档的指针:)@practechal我添加了隐式导入以备将来使用:)