协程四(CoroutineScope)

2023-07-06  本文已影响0人  coke613
定义协程必须指定其CoroutineScope,它会跟踪所有协程,同样它还可以跟踪取消它所启动的协程.

协程作用域:

coroutineScope 与runBlocking 协程作用域
coroutineScope 与 supervisorScope 协程作用域
        runBlocking {
            coroutineScope {
               val job1 =  launch {
                   delay(400)
                   println("job1 fininsh")
               }


                val job2 = launch {
                    delay(200)
                    println("job2 fininsh")    // ① 程序打印   job2 fininsh
                   throw IllegalArgumentException()    // ② 程序崩溃 协程体取消
                }
            }
        }
        runBlocking {
            coroutineScope {
               val job1 =  launch {
                   delay(400)
                   println("job1 fininsh")   // ② 程序打印   job1 fininsh
               }


                val job2 = async {
                    delay(200)
                    println("job2 fininsh")   //  ① 程序打印   job2 fininsh
                    "HHH"
                   throw IllegalArgumentException()
                }
            }
        }

上一篇下一篇

猜你喜欢

热点阅读