我使用带有 "org.mongodb.scala" %% "mongo-scala-driver" % "1.0.1" 的 playframework 并拥有该代码:
val collection = Mongo.db.getCollection("regionAuth")
def getRegions = {
val find: Observable[Document] = collection.find()
Logger.info("regions searching")
find.subscribe(new Observer[Document] {
override def onError(e: Throwable): Unit = Logger.error("regions error", e)
override def onSubscribe(subscription: Subscription): Unit = Logger.info("subscribed")
override def onComplete(): Unit = Logger.info("regions done")
override def onNext(result: Document): Unit = Logger.info("region accepted")
})
find.map { region =>
Logger.info("region accepted by map")
region
}
find.foreach(_ => Logger.info("region accepted by foreach"))
find.toFuture().onComplete {
case Success(r) => Logger.info("regions accepted as future seq " + r.size)
case Failure(e) => Logger.error("regions error as future", e)
}
find
}
它打印:
[信息] 应用程序 - 区域搜索
[信息] 应用程序 - 已订阅
[信息] 应用程序 - foreach 接受的区域
[信息] 应用程序 - foreach 接受的区域
[信息] 应用程序 - foreach 接受的区域
[信息] 应用程序 - 被接受为未来 seq 3 的区域
为什么subscribe的事件和地图不起作用?