From 1a3a37b9b89fe632ee514c97271470c18f09ab0c Mon Sep 17 00:00:00 2001 From: sacOO7 Date: Sat, 9 Nov 2024 16:56:46 +0530 Subject: [PATCH] Appending current coroutineContext to make sure running/pending jobs cancelled when atomicCoroutineScope.cancel is called --- .../src/main/java/com/ably/chat/AtomicCoroutineScope.kt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/chat-android/src/main/java/com/ably/chat/AtomicCoroutineScope.kt b/chat-android/src/main/java/com/ably/chat/AtomicCoroutineScope.kt index 390ca89..886ba9c 100644 --- a/chat-android/src/main/java/com/ably/chat/AtomicCoroutineScope.kt +++ b/chat-android/src/main/java/com/ably/chat/AtomicCoroutineScope.kt @@ -2,9 +2,11 @@ package com.ably.chat import java.util.concurrent.PriorityBlockingQueue import kotlin.coroutines.cancellation.CancellationException +import kotlin.coroutines.coroutineContext import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelChildren import kotlinx.coroutines.launch @@ -66,7 +68,8 @@ class AtomicCoroutineScope(private val scope: CoroutineScope = CoroutineScope(Di private suspend fun safeExecute(job: Job) { try { - scope.launch { + // Appends coroutineContext to cancel current/pending jobs when AtomicCoroutineScope is cancelled + scope.launch(coroutineContext) { try { val result = job.coroutineBlock(this) job.deferredResult.complete(result) @@ -81,6 +84,7 @@ class AtomicCoroutineScope(private val scope: CoroutineScope = CoroutineScope(Di /** * Cancels ongoing and pending operations with given error. + * See [Coroutine cancellation](https://kt.academy/article/cc-cancellation#cancellation-in-a-coroutine-scope) for more information. */ @Synchronized fun cancel(message: String?, cause: Throwable? = null) {