'Coroutines changing scopes

I want to do the below with coroutines but not sure what's the right way to do this and if there is another way to do this. What I want is this: I want to create a lib that uses its own coroutine scope for requests/responses while allowing cancelling this coroutine scope when cancel method is called without cancelling the outer scope from which method of the lib is called. For example, when a client code that has their own coroutine scope calls my lib method, I want to switch from their scope to my coroutine scope. And then, when some other coroutine/code calls cancel, I want to cancel my coroutine scope(and all it's children coroutines) without cancelling the outer scope that called the method. Example of code:

private val myCoroutineScope = CoroutineScope(...)

suspend fun myLibMethod(){
   //execute the this method in the myCoroutineScope
}

suspend fun cancel(){
   myCoroutineScope.cancel()
}

For now I came up with this solution which I am not sure if it's the right one and if it's reliable:

suspend fun myLibMethod(){
   withContext(myCoroutineScope.coroutineContext){
     ....
   }
}

I wrote and tried this code which does not print Done and cancels I think the outer scope as well because of the exception:

runBlocking {

            val coroutineScope = CoroutineScope(Dispatchers.Default)

            println("Launching coroutine that will stop the coroutine scope after 2 seconds.")
            launch(Dispatchers.Default) {
                delay(2_000)
                coroutineScope.cancel()
            }

            println("Changing coroutine context to the coroutine scope' context")
            withContext(coroutineScope.coroutineContext){
                delay(10_000)
            }
            println("Done!")
        }

Actually, the above works - it does not cancel the outer scope if I catch the exception(isActive returns true). I am not still sure though if that's the best solution. I also see an example with Deferred that is cancelled when the lib's scope is cancelled(which looks better). Maybe someone has faced a similar problem and knows a better solution



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source