Search code examples
kotlinkotlinx.coroutineskotlin-coroutines

Kotlin coroutine scope definition


Imagine that I have a coroutine scope called CryptographyScope:

object CryptographyScope : CoroutineScope {
     override val coroutineContext: CoroutineContext =
        Dispatchers.IO + CoroutineName("CryptographyScope")
}

So, in many places in my application I call CryptographyScope.async.

CryptographyScope.async {
    cryptographyService.decrypt(value) 
} 
  • What happens when one of the cryptographyService.decrypt(value) fails and throws an exception? Does it cancel every coroutine that uses CryptographyScope in the application at the moment of execution?

  • Should the CryptographyScope be a singleton?


Solution

  • CoroutineScope defines a scope where you contain, delimit and keep track of all concurrent operations and tying them to the lifecycle of your application entity.

    I was going to call decrypt through the custom scope I had created CryptographyScope. But, this isn't right since I don't have a any entity with defined lifecycle so won't be able to avoid leak happening.

    The correct thing to do is:

    fun decryptAll() = coroutineScope {
        async { 
            cryptographyService.decrypt(value1) 
        }
        async { 
            cryptographyService.decrypt(value2) 
        }
    }