If I have a suspend function that launches a backg...
# coroutines
j
If I have a suspend function that launches a background job i.e. :
Copy code
suspend fun doSomething() = withContext(coroutineContext) { 
   launch { 
       while(isActive) { 
           println("I'm Still Here")
           delay(1000)
       }
   } 
}
If that suspend function get’s cancelled due to an OOM exception how do I insure that the job that was launch is also cancelled?
o
since
withContext
opens a new Job that is the child of whatever called the suspend function, and
launch
creates a new Job that is the child of
withContext
, it will all be cancelled automatically
though if it's due to OOM, there might not be enough memory to propagate the cancellation?
j
Yes, assuming you use
withContext
but that forces this to no longer be a background task in that this function does not resolve until the job resolve. The naive approach would be something like this:
Copy code
suspend fun doSomething() { 
   GlobalScope.launch { 
       while(isActive) { 
           println("I'm Still Here")
           delay(1000)
       }
   } 
}
Obviously cancellations don’t get respected correctly there, but i’m trying to figure out how to achieve the same background behavior with the ability to propogate the cancellations.
o
you could obviously just pull the job from `doSomething`'s context, and check its
isActive
e.g.
Copy code
val job = coroutineContext[Job]!!
GS.launch {
  while (isActive && job.isActive) { ... }
}
j
The problem with doing that is that if the parent is cancelled with OOM your reliant on the while loop re-evaluating the condition which might not be possible if your already out of memory.
o
cancellation is always cooperative, so I don't think this really changes anything
if it throws another OOM, then it'll cancel anyways
j
If the child throws OOM on the GlobalScope the parent will not know about it.