0

我使用带有 "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的事件和地图不起作用?

4

1 回答 1

0

我希望还不算晚。如果这是一个没有其他任何东西运行的独立应用程序,您必须等到未来完成。

...
val future = find.toFuture()
future.onComplete {
  case Success(r) => Logger.info("regions accepted as future seq " + r.size)
  case Failure(e) => Logger.error("regions error as future", e)
}

scala.concurrent.Await.result(future)
find
于 2016-10-12T05:33:14.567 回答