Hi! is there any stable API alternative for job.in...
# coroutines
n
Hi! is there any stable API alternative for job.invokeOnCompletion(onCancelling = true)? (see thread for example of what I'm trying to achieve) I have approach 1 (without onCancelling = true) where it will deadlock (in prod, it wouldn't deadlock but also won't cancel), so I can't use that. Then I tried suspendCancellableCoroutine in approach 2, which actually works, but seems like wrong tool for the job (my API isn't callback based). And there is approach 3, which works but uses internal coroutine api onCancelling=true. Am I missing any better way?
🧵 1
What I'm trying to achieve: (moved to thread)
Copy code
import android.os.CancellationSignal
import android.os.OperationCanceledException
@RunWith(RobolectricTestRunner::class)
class CancellationSignalTest {

    private fun legacyApi(signal: CancellationSignal) {
        // in prod, this is Android platform API I can't change
        runBlocking {
            while (true) {
                signal.throwIfCanceled()
                delay(10.milliseconds)
                // of course the API actually returns something, but I'm working on cancellation so this is omitted here
            }
        }
    }

    private suspend inline fun T runWithCancellationSignal(block: (CancellationSignal) -> T): T {
        val signal = CancellationSignal()
        val job = currentCoroutineContext().job
        val listener = job.invokeOnCompletion { e ->
            if (e is CancellationException) signal.cancel()
        }
        try {
            return block(signal)
        } catch (e: OperationCanceledException) {
            throw CancellationException(null, e)
        } finally {
            listener.dispose()
        }
    }

    //@Test
    fun test1DoesNotDeadlock() {
        runBlocking {
            withTimeout(1000.milliseconds) {
                val job = launch {
                    runWithCancellationSignal(::legacyApi)
                }
                delay(50.milliseconds)
                job.cancelAndJoin()
            }
        }
    }

    private suspend inline fun T runWithCancellationSignal2(
        crossinline block: (CancellationSignal) -> T,
        noinline onCancellation: ((cause: Throwable, value: T, context: CoroutineContext) -> Unit)?
    ): T {
        return suspendCancellableCoroutine { continuation ->
            val signal = CancellationSignal()
            continuation.invokeOnCancellation { signal.cancel() }
            try {
                continuation.resume(block(signal), onCancellation)
            } catch (e: OperationCanceledException) {
                continuation.resumeWithException(CancellationException(null, e))
            } catch (t: Throwable) {
                continuation.resumeWithException(t)
            }
        }
    }

    @Test
    fun test2DoesNotDeadlock() {
        runBlocking {
            withTimeout(1000.milliseconds) {
                val job = launch {
                    runWithCancellationSignal2(::legacyApi, null)
                }
                delay(50.milliseconds)
                job.cancelAndJoin()
            }
        }
    }

    @OptIn(InternalCoroutinesApi::class)
    private suspend inline fun T runWithCancellationSignal3(block: (CancellationSignal) -> T): T {
        val signal = CancellationSignal()
        val job = currentCoroutineContext().job
        val listener = job.invokeOnCompletion(onCancelling = true) { e ->
            if (e is CancellationException) signal.cancel()
        }
        try {
            return block(signal)
        } catch (e: OperationCanceledException) {
            throw CancellationException(null, e)
        } finally {
            listener.dispose()
        }
    }

    @Test
    fun test3DoesNotDeadlock() {
        runBlocking {
            withTimeout(1000.milliseconds) {
                val job = launch {
                    runWithCancellationSignal3(::legacyApi)
                }
                delay(50.milliseconds)
                job.cancelAndJoin()
            }
        }
    }
}
w
Option 2 seems the most idiomatic, if that works for you, then it seems perfect! The other two options use
currentCoroutineContext().job
, which is risky, since you're working on the job you get from "above", which is also why the first example deadlocks. The
Job
that calls your function waits for your to finish, and thus, it never completes. (Also,
invokeOnCompletion
has some footguns that can introduce very subtle cancellation race conditions if not used correctly)
v
The lack of an idiomatic API for this specific case and possible workarounds are discussed in #4117.
n
Thanks for the advice and link!