Created
December 2, 2019 19:53
-
-
Save juliuscanute/5bd7cfe1b9d3035f13af5e2e3c148ec2 to your computer and use it in GitHub Desktop.
[Custom Coroutine Scope] #kotlin #coroutine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)` | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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