Skip to content

Instantly share code, notes, and snippets.

@kostapc
Forked from juliuscanute/CustomScope.kt
Created March 1, 2021 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kostapc/34626189ca4d6aa49c217764f00c6525 to your computer and use it in GitHub Desktop.
Save kostapc/34626189ca4d6aa49c217764f00c6525 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