- class ExampleClass {
- ...
- fun exampleMethod() {
- // Handle to the coroutine, you can control its lifecycle
- val job = scope.launch {
- // New coroutine
- }
- if (...) {
- // Cancel the coroutine started above, this doesn't affect the scope
- // this coroutine was launched in
- job.cancel()
- }
- }
- }
我们通过Job可以获取当前协程的运行状态,还可以随时取消协程。
- val job = GlobalScope.launch(start = CoroutineStart.LAZY) {
- println("执行在协程中...")
- delay(1000L)
- println("执行完毕...")
- }
- job.start()
- var job = GlobalScope.launch {
- println("执行在协程中...")
- delay(1000L)
- println("执行完毕...")
- }
- ...
- override fun onDestroy() {
- job.cancel()
- super.onDestroy()
- }
- val exceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable ->
- YYLogUtils.e(throwable.message ?: "Unkown Error")
- }
- val job = GlobalScope.launch(Dispatchers.Main + exceptionHandler) {
-