Skip to content

Commit

Permalink
Add awaitCancellation()
Browse files Browse the repository at this point in the history
Resolves issue Kotlin#2213
  • Loading branch information
LouisCAD committed Sep 2, 2020
1 parent fe2fedc commit aa2c17d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
8 changes: 8 additions & 0 deletions kotlinx-coroutines-core/common/src/Await.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ package kotlinx.coroutines
import kotlinx.atomicfu.*
import kotlin.coroutines.*

/**
* Suspends until cancellation, in which case it will throw a [CancellationException].
*
* Handy because it returns [Nothing], allowing it to be used in any coroutine,
* regardless of the required return type.
*/
public suspend inline fun awaitCancellation(): Nothing = suspendCancellableCoroutine {}

/**
* Awaits for completion of given deferred values without blocking a thread and resumes normally with the list of values
* when all deferred computations are complete or resumes with the first thrown exception if any of computations
Expand Down
27 changes: 27 additions & 0 deletions kotlinx-coroutines-core/common/test/AwaitCancellationTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.coroutines

import kotlin.test.*

class AwaitCancellationTest : TestBase() {

@Test
fun testCancellation() = runTest(expected = { it is CancellationException }) {
expect(1)
coroutineScope {
val deferred: Deferred<Nothing> = async {
expect(2)
awaitCancellation()
}
yield()
expect(3)
require(deferred.isActive)
deferred.cancel()
finish(4)
deferred.await()
}
}
}

0 comments on commit aa2c17d

Please sign in to comment.