https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

Dico

05/04/2019, 5:58 PM
Developers are recommended to use non-suspend
fun CoroutineScope.xxxAsync()
for functions that launch something and return immediately, and
suspend fun xxx()
for functions that suspend/block until all of their execution completes. Much of the kotlinx.coroutines API uses lambdas that are suspend and have a
CoroutineScope
receiver. The
CoroutineScope
allows developers to write coroutines with cancellability in mind - by checking
isActive
. What's the best way to get access to this in a
suspend fun
?
I suppose you can use
coroutineContext[Job]!!.isActive
, but this is more ugly. Maybe use
coroutineScope { }
if it's needed?
l

louiscad

05/04/2019, 6:07 PM
Use
coroutineScope
. For your use case though, maybe all you need is
coroutineContext.ensureActive()
so it throws the
CancellationException
in tight loops?
d

Dico

05/05/2019, 2:13 PM
Oh I didn't know that exists. Cool
l

louiscad

05/05/2019, 3:15 PM
It has been added in 1.2.0
4 Views