Skip to content

Instantly share code, notes, and snippets.

@juliuscanute
Created December 2, 2019 19:53
Show Gist options
  • Save juliuscanute/5bd7cfe1b9d3035f13af5e2e3c148ec2 to your computer and use it in GitHub Desktop.
Save juliuscanute/5bd7cfe1b9d3035f13af5e2e3c148ec2 to your computer and use it in GitHub Desktop.
[Custom Coroutine Scope] #kotlin #coroutine
class CustomScope : CoroutineScope {
private var parentJob = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + parentJob
fun onStart() {
parentJob = Job()
}
fun onStop() {
parentJob.cancel()
// You can also cancel the whole scope with `cancel(cause: CancellationException)`
}
}
fun main() {
val scope = CustomScope()
scope.launch {
println("Launching in custom scope")
}
scope.onStop() //cancels all the coroutines
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment