This is not yet part of the Future API, but may be added as an extension in the future.
As a workaround, you can use firstCompletedOf to wrap 2 futures - the future you want to cancel and the future that comes from custom Promise . Then you can cancel the future created in this way without fulfilling the promise:
def cancellable[T](f: Future[T])(customCode: => Unit): (() => Unit, Future[T]) = { val p = Promise[T] val first = Future firstCompletedOf Seq(p.future, f) val cancellation: () => Unit = { () => first onFailure { case e => customCode} p failure new Exception } (cancellation, first) }
Now you can call this in any future to get a "cancelable wrapper". Usage example:
val f = callReturningAFuture() val (cancel, f1) = cancellable(f) { cancelTheCallReturningAFuture() } // somewhere else in code if (condition) cancel() else println(Await.result(f1))
EDIT:
For a detailed discussion of cancellation, see Chapter 4 in Teaching Parallel Programming in Scala .
axel22 Apr 15 '13 at 7:50 2013-04-15 07:50
source share