且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

取消Scala中的未来和承诺

更新时间:2022-05-18 22:51:34

scala.concurrent.Future是只读的,因此一个读者无法搞乱事情。对于其他读者。

scala.concurrent.Future is read-only, so one reader cannot mess things up for the other readers.

似乎您应该能够实现所需的内容,如下所示:

It seems like you should be able to implement what you want as follows:

def cancellableFuture[T](fun: Future[T] => T)(implicit ex: ExecutionContext): (Future[T], () => Boolean) = {
  val p = Promise[T]()
  val f = p.future
  p tryCompleteWith Future(fun(f))
  (f, () => p.tryFailure(new CancellationException))
}

val (f, cancel) = cancellableFuture( future => {
  while(!future.isCompleted) continueCalculation // isCompleted acts as our interrupted-flag

  result  // when we're done, return some result
})

val wasCancelled = cancel() // cancels the Future (sets its result to be a CancellationException conditionally)