ansman
05/01/2019, 4:49 PMmyScope.launch {
// If the job is canceled before createResourceSync() returns the resource is lost in transit
val resource = withContext(Dispatchers.default) { createResourceSync() }
try {
} finally {
resource.delete()
}
}
Dominaezzz
05/01/2019, 6:31 PMmyScope.launch {
// If the job is canceled before createResourceSync() returns the resource is lost in transit
val resource: ResourceType
try {
resource = withContext(Dispatchers.Default) { createResourceSync() }
} finally {
resource.delete()
}
}
resource
has to be a nullable var and resource?.delete()
. Can't check right now.ansman
05/01/2019, 6:34 PMDominaezzz
05/01/2019, 6:34 PMdelete
will be called.ansman
05/01/2019, 6:35 PMDominaezzz
05/01/2019, 6:36 PMansman
05/01/2019, 6:36 PMDominaezzz
05/01/2019, 6:37 PMCancellationException
or something.ansman
05/01/2019, 6:37 PMDominaezzz
05/01/2019, 6:38 PMcreateResourceSync
?ansman
05/01/2019, 6:39 PMrunBlocking {
val job = launch {
var resource: String? = null
try {
resource = withContext(Dispatchers.Default) {
Thread.sleep(100)
"Hello"
}
} finally {
println("Resource is $resource")
}
}
delay(10)
job.cancel()
}
Dominaezzz
05/01/2019, 6:39 PMmyScope.launch {
// If the job is canceled before createResourceSync() returns the resource is lost in transit
val resource: ResourceType
try {
withContext(Dispatchers.Default) {
resource = createResourceSync()
}
} finally {
resource.delete()
}
}
ansman
05/01/2019, 6:40 PM"Resource is null"
Dominaezzz
05/01/2019, 6:42 PMwithContext
but not within it. resource would have been set.ansman
05/01/2019, 6:43 PMcreateResourceSync
hasn’t returned yetval ref: AtomicReference<Resource?> = AtomicReference()
withContext(Dispatchers.Default) {
ref.set(createResourceSync())
if (!isActive) {
ref.getAndSet(null)?.delete()
}
}
val resource = ref.getAndSet(null)
try {
// Do stuff with resource
} finally {
resource?.delete()
}
Dominaezzz
05/01/2019, 6:46 PMansman
05/01/2019, 6:46 PMDominaezzz
05/01/2019, 6:46 PMwithContext
is synchronous.ansman
05/01/2019, 6:48 PMDominaezzz
05/01/2019, 6:48 PMansman
05/01/2019, 6:53 PMcreateResourceSync
is running the exception will be thrown (and enter the finally block) while still running createResourceSync
so in a sense it is concurrent in some circumstancesDominaezzz
05/01/2019, 6:58 PMansman
05/01/2019, 6:59 PMDominaezzz
05/01/2019, 6:59 PMwithContext
🙂ansman
05/01/2019, 7:00 PMDominaezzz
05/01/2019, 7:01 PMfinally
would run and resource
will be set.ansman
05/01/2019, 7:02 PMNonCancellable
but it will still cause issues if the code within withContext
uses any coroutinesNonCancellable
is that withContext
won’t throw so you’d have to check isActive
manually