What is the proper way in a simple suspend functio...
# coroutines
t
What is the proper way in a simple suspend function to check if it's running inside a job and if that job is cancelled?
g
Why do you need this? every suspend point automatically checks for Job cancellation
You can get job using:
coroutineContext[Job]
but use this to check for cancellation doesn’t make a lot of sense Instead you can use isActive, or just call any suspend function or if you don’t need it you can use
yield()
which is an empty suspend point, if job is cancelled you suspend function will never return after
yield()
or other suspend call
t
Because this is a small simple function that would require way too much refactoring 🙂 it calls another suspending function and if the job is not cancelled it push the result to observers.
Currently using yield but it gives other coroutines priority before pushing result when not cancelled.
g
yield just allows other coroutines chance to be disputched
I still don’t understand why yield or isActive is not work for you
Looks like some problem in your code if you rely on coroutine dispatching order
t
Nope yield just push other coroutine when contention, I prefer the push to be as fast as possible when not cancelled. It's not vital and mandatory just better.
And I just missed the coroutineContext[Job] to get access to the isActive 🙂
Thanks for the missing part
g
there is top level isActive, you don’t need
coroutineContext[Job]
to access it
t
That class already have a isActive val 😉
g
I would rename it then %) Because
isActive
is available in scope of any coroutine
But also you can import it with different name
Copy code
import kotlinx.coroutines.isActive as isActiveCoroutine
t
This is part of a larger public API I can't rename, import does not work I get
Copy code
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val CoroutineContext.isActive: Boolean defined in kotlinx.coroutines
public val CoroutineScope.isActive: Boolean defined in kotlinx.coroutines
g
What do you mean “does not work”? I see in your error message that you use
isActive
, not a renamed one
Just checked, works for me
t
It does not work in a class that does not extend a coroutineScope
g
yes, correct
otherwise you can use coroutineContext.isActive
t
Copy code
import kotlinx.coroutines.isActive as isActiveCoroutine

class Renderer {

	suspend fun checkStatus() {
		if (isActiveCoroutine) {
		}
	}
}
for reference 😞
g
use
coroutineContext.isActive
for suspend functions
t
What does it check ? 🙂 Current Job, ParentJob, the context itself? I'll stick with coroutineContext[Job] at least it's clear what it check
g
This is just an alias for
coroutineContext[Job]?.isActive == true
Also if you press F1 on this function you can see documentation
t
Currently having issues with AS not using the source and doc for custom coroutines build 😞 But ok thanks will use that then.