Skip to content
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

Rethrow AbortFlowException upon cancellation (#4034) #4254

Merged
merged 1 commit into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 3 additions & 0 deletions kotlinx-coroutines-core/common/src/flow/operators/Limit.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package kotlinx.coroutines.flow

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.internal.*
import kotlin.coroutines.*
import kotlin.jvm.*
import kotlinx.coroutines.flow.flow as safeFlow
import kotlinx.coroutines.flow.internal.unsafeFlow as flow
Expand Down Expand Up @@ -133,5 +134,7 @@ internal suspend inline fun <T> Flow<T>.collectWhile(crossinline predicate: susp
collect(collector)
} catch (e: AbortFlowException) {
e.checkOwnership(collector)
// The task might have been cancelled before AbortFlowException was thrown.
coroutineContext.ensureActive()
}
}
21 changes: 20 additions & 1 deletion kotlinx-coroutines-core/common/test/flow/terminal/FirstTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package kotlinx.coroutines.flow

import kotlinx.coroutines.testing.*
import kotlinx.coroutines.*
import kotlinx.coroutines.CoroutineStart.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.internal.*
import kotlin.test.*
import kotlin.time.*

class FirstTest : TestBase() {
@Test
Expand Down Expand Up @@ -173,4 +175,21 @@ class FirstTest : TestBase() {

assertFailsWith<CancellationException> { flow.first() }
}
}

@Test
fun testFirstThrowOnCancellation() = runTest {
val job = launch(start = UNDISPATCHED) {
flow {
try {
emit(Unit)
} finally {
runCatching { yield() }
finish(2)
}
}.first()
expectUnreached()
}
expect(1)
job.cancel()
}
jxdabc marked this conversation as resolved.
Show resolved Hide resolved
}