-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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
kotlin.coroutines.channels.awaitClose: JobCancellationException #1762
Comments
Could you please elaborate on why? And additional non-suspending
|
I think what confused me is the statement in the docs:
This made it sound like a good fit for a cleanup function. It waits until the coroutine/channel gets closed/canceled to finally do some last peace of work. It never came to my mind that it would throw an exception if it is already canceled or closed! Intuitively, I thought, it would just continue calling the block (which it does, but throws the exception also) Maybe my intuition on this function is just different because I used it in that specific context |
Thanks! I will improve the documentation of |
The But the And the JobCancellationException is really confused because it will have less stack trace, just |
@ExperimentalCoroutinesApi
fun main(args: Array<String>) = runBlocking {
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
scope.launch {
getFlow().collect {
println(it)
}
}
Thread.sleep(10)
scope.cancel()
Thread.sleep(1000)
}
@ExperimentalCoroutinesApi
fun getFlow(): Flow<String> {
return callbackFlow {
Thread {
for (i in 0 until 10) {
val temp = "flow ==> $i"
offer(temp)
Thread.sleep(5)
}
}.start()
Thread.sleep(1000)
}
// no awaitClose for better testing
} This is an example I just test because I got lots of crashes because of the JobCancellationException. It will not just happen every time, but it's really frequently. |
Yes, |
I wrote an extension function to prevent JobCancellationException in our app. Maybe it will be useful for someone who still looking for a solution. You must replace inline fun <reified E : Any> ProducerScope<E>.offerSafe(element: E) {
if (isActive) {
offer(element)
}
} |
The
awaitClose
function currently throws aJobCancellationException
if the job was canceled before calling the function.I would have personally expected that the block passed to
awaitClose { }
gets executed without throwing this exception.Sample code:
Coroutines version 1.3.3
Kotlin version 1.3.61
The text was updated successfully, but these errors were encountered: