https://kotlinlang.org logo
Title
s

simon.vergauwen

01/03/2019, 7:27 PM
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.
val def = thisWasPassedToMe()
val result = withContext(NonCancelable) {
  def.await()
}
b

bdawg.io

01/03/2019, 7:31 PM
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

simon.vergauwen

01/03/2019, 7:34 PM
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

bdawg.io

01/03/2019, 7:44 PM
No, a
Deferred
is just a reference handle to the state of the coroutine
s

simon.vergauwen

01/03/2019, 7:51 PM
Alright thanks. Guess I'll have to work around it.
g

groostav

01/03/2019, 9:06 PM
@simon.vergauwen whats the parent coroutine factory? assumjing its either a
launch
or
runBlocking
you can use
CoroutineStart.ATOMIC
eg
launch(CoroutineStart.ATOMIC){
  val def = thisWasPassedToMe()
  def.await()
}
also of course, finally blocks function through cancellation:
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

groostav

01/03/2019, 9:23 PM
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

simon.vergauwen

01/03/2019, 9:26 PM
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