kotlin 协程。作用域的取消,兄弟协程的取消,协程取消会异常

 作用域的取消

   private fun testScopeCancel() = runBlocking<Unit> {
        val scope = CoroutineScope(Dispatchers.Default)
        scope.launch {
            delay(1000)
            Log.e(TAG, "job1 finish")
        }
        scope.launch {
            delay(1000)
            Log.e(TAG, "job2 finish")
        }
        delay(100)
        scope.cancel()
    }

整个协程都会被取消,

如果我们想仅仅取消部分协程呢?

    private fun testBrotherScopeCancel() = runBlocking<Unit> {
        val scope = CoroutineScope(Dispatchers.Default)
        val job1 = scope.launch {
            delay(1000)
            Log.e(TAG, "job1 finish")
        }
        val job2 = scope.launch {
            delay(1000)
            Log.e(TAG, "job2 finish")
        }
        delay(100)

        job1.cancel()
        Log.e(TAG, "协程的作用域要被取消啦")
    }

job是可以取消的,同理作用域也可以进行取消操作。

    private fun cancelilationExcepiton() = runBlocking {
        val job1 = GlobalScope.launch {
            try {
                delay(1100)
                Log.e(TAG, "job1 finish")
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        delay(100)
        job1.cancel(CancellationException("取消"))
        job1.join()
    }

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/125252914