Skip to content

Add awaitCancellation() #2225

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, it would be great to show some small practical example here, if you have one in mind.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added two examples. I failed to find simpler examples for now, but it's not public API so it can be changed in the future.

Also, I know trySend doesn't exist yet, but I thought it would look nicer than runCatching { offer(…) } or a try/catch.

* 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()
}
}
}