Can I make a `Deferred<A>` `NonCancelable` b...
# coroutines
s
Can I make a
Deferred<A>
NonCancelable
by wrapping and awaiting it in a
withContext
block like below. And how does its scope get (re)wired correctly? Snippet seems to work although I don't quite understand it.
Copy code
val def = thisWasPassedToMe()
val result = withContext(NonCancelable) {
  def.await()
}
b
You will still get a
CancellationException
thrown if the backing Job for
def
gets cancelled
NonCancellable
will just make sure that your
withContext
itself doesn’t exit from being cancelled itself
s
I'm not sure I 100% understand that last bit. Only what gets created within
withContext
is NonCancelable?
Is there another way to make an existing Deferred NonCancelable?
b
No, a
Deferred
is just a reference handle to the state of the coroutine
s
Alright thanks. Guess I'll have to work around it.
g
@simon.vergauwen whats the parent coroutine factory? assumjing its either a
launch
or
runBlocking
you can use
CoroutineStart.ATOMIC
eg
Copy code
launch(CoroutineStart.ATOMIC){
  val def = thisWasPassedToMe()
  def.await()
}
also of course, finally blocks function through cancellation:
Copy code
suspend fun doStuffWithThingPassedToMe(){
  try {
    val def = thisWasPassedToMe()
  }
  finally {
    //this will fire in all cercomstances (except abandonment!)
  }
}
It’s within a suspend function. However this
Deferred
is guaranteed to have never run.
g
sorry so your calling this library function or your looking for an implementation of
release
?
its funny I've read the scala red-book but I still dont understand arrow
s
The point of this function is to acquire some resource. This resource is provided through a
Deferred<A>
that has never run and is lazily run.
acquire is guaranteed not to be cancelled, and the
release
is guaranteed to be called. There is also a
use
function which you can use to consume the `acquire`d resource.
In other words you can use this function to compose different lazily run
Deferred
to safely consume and release resources with a guarantee not to leak.
We use this to provide a generic API for data types with similar behaviours like
Observable
,
Flux
,
IO
, …
If you have any questions about Arrow feel free to swing by #arrow to ask questions and we’ll be glad to help!
arrow 1