Returns a future that can unsubscribe from this promise's notifications via cancelation.
Returns a future that can unsubscribe from this promise's notifications via cancelation.
val promise = CancelablePromise[Int]() val future1 = promise.future val future2 = promise.future for (r <- future1) println(s"Future1 completed with: $$r") for (r <- future2) println(s"Future2 completed with: $$r") // Unsubscribing from the future notification, but only for future1 future1.cancel() // Completing our promise promise.success(99) //=> Future2 completed with: 99
Note that in the above example future1
becomes non-terminating
after cancellation. By unsubscribing its listener, it will never
complete.
This helps with avoiding memory leaks for futures that are being timed-out due to promises that take a long time to complete.
Low-level subscription method that registers a callback to be called when this promise will complete.
Low-level subscription method that registers a callback to be called when this promise will complete.
val promise = CancelablePromise[Int]() def subscribe(n: Int): Cancelable = promise.subscribe { case Success(str) => println(s"Callback ($$n) completed with: $$str") case Failure(e) => println(s"Callback ($$n) completed with: $$e") } val token1 = subscribe(1) val token2 = subscribe(2) // Unsubscribing from the future notification token1.cancel() // Completing our promise promise.success(99) //=> Callback (2) completed with: 99
UNSAFE PROTOCOL: the implementation does not protect
against stack-overflow exceptions. There's no point in doing it
for such low level methods, because this is useful as middleware
and different implementations will have different ways to deal
with stack safety (e.g. monix.eval.Task
).
is a callback that will be called when the promise completes with a result, assuming that the returned cancelable token isn't canceled
a cancelable token that can be used to unsubscribe the given callback, in order to prevent memory leaks, at which point the callback will never be called (if it wasn't called already)
CancelablePromise
is a scala.concurrent.Promise implementation that allows listeners to unsubscribe from receiving future results.It does so by:
Being able to unsubscribe listeners helps with avoiding memory leaks in case of listeners or futures that are being timed-out due to promises that take a long time to complete.
future
subscribe