05nelsonm / kmp-tor

Kotlin Multiplatform Library for embedding Tor into your applications
Apache License 2.0
33 stars 5 forks source link

`awaitAsync` is not cancellable #392

Closed 05nelsonm closed 4 months ago

05nelsonm commented 5 months ago

Current implementation utilizes invokeOnCompletion for the parent job in order to cancel the EnqueuedJob, but because of the withContext(NonCancellable) { latch.join() }, we are detached from the parent job and will not get the invokeOnCompletion callback.

@Test
fun givenDetachedJob_whenCancelled_thenInvokeOnCompletionAfterJoin() = runTest {
    val latch = Job()

    val job = launch {
        withContext(NonCancellable) { latch.join() }
        println("JOB[ending]")
    }

    job.invokeOnCompletion { println("JOB[completed]") }

    withContext(Dispatchers.Default) { delay(50.milliseconds) }
    println("JOB[cancelling]")
    println("$job")
    job.cancel()
    println("$job")

    withContext(Dispatchers.Default) { delay(50.milliseconds) }
    println("LATCH[completing]")
    println("$job")
    latch.complete()

    withContext(Dispatchers.Default) { delay(50.milliseconds) }
    println("JOB[$job]")
    println("LATCH[$latch]")
}
JOB[cancelling]
"coroutine#3":StandaloneCoroutine{Active}@b7c4869
"coroutine#3":StandaloneCoroutine{Cancelling}@b7c4869
LATCH[completing]
"coroutine#3":StandaloneCoroutine{Cancelling}@b7c4869
JOB[ending]
JOB[completed]
JOB["coroutine#3":StandaloneCoroutine{Cancelled}@b7c4869]
LATCH[JobImpl{Completed}@19b93fa8]