在阻塞调用中包装异步代码

时间:2016-04-27 09:41:23

标签: scala

我在MongoDB中插入记录:

val observable: Observable[Completed] = collection.insertOne(doc)

observable.subscribe(new Observer[Completed] {
  override def onNext(result: Completed): Unit = { println("Inserted"); }
  override def onError(e: Throwable): Unit = { println(" \n\nFailed " + e + "\n\n"); fail() }
  override def onComplete(): Unit = { println("Completed"); }
})

即使调用onError回调,测试也会通过。这是因为insertOne是一个异步方法,测试在调用onError之前完成。我想将insertOne方法包装到阻塞调用中,因此在设置subscribe值之前不会调用observable

在Scala中是否存在实现此目的的惯用方法?

1 个答案:

答案 0 :(得分:2)

同步阻止异步操作的最简单方法是在Future上使用Await.result。由于MongoCollection.insertOne会返回Observable[Complete],因此您可以在其上使用隐式ScalaObservable.toFuture

val observable = collection.insertOne(doc)
Await.result(observable.toFuture, Duration.Inf)

observable.subscribe(new Observer[Completed] {
  override def onNext(result: Completed): Unit = { println("Inserted"); }
  override def onError(e: Throwable): Unit = { println(" \n\nFailed " + e + "\n\n"); fail() }
  override def onComplete(): Unit = { println("Completed"); }
})