Are there are drawback to the `currentCoroutineCon...
# coroutines
a
Are there are drawback to the
currentCoroutineContext()
function? I want to cancel my listener when my coroutine is no longer active. I don’t have access to the scope, but I can use
currentCoroutineContext()
since i’m inside a suspend function. Could this have any negative impact? Like memory leak or a false-positive?
Copy code
private suspend fun doEffects(colorChangeCallback: OnColorChangedCallback, valueAnimator: ValueAnimator) {
    val context: CoroutineContext = currentCoroutineContext()
    valueAnimator.addUpdateListener {
        if (context.isActive) {
            // Do your work
        } else {
            // Cancel other work
            valueAnimator.cancel()
        }
    }
}
👀 1
d
See this thread from yesterday: https://kotlinlang.slack.com/archives/C1CFAFJSK/p1652964299132039 If you're outside of a coroutine (for example, if you call your function from
suspend fun main
),
currentCoroutineContext
will be empty.
a
Thanks, I’ll look into it
j
Why not use
suspendCancellableCoroutine
and
invokeOnCancellation
?
a
Did not know of it
👍 1