Kotlin GlobalScope 和 CoroutineScope
作者:mmseoamin日期:2024-01-19
package com.tiger.mykotlinapp.scope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
fun main() {
    val  globalScope = GlobalScope
    globalScope.launch {
        delay(3000)
        println("hello")
    }
    globalScope.launch {
        delay(3000)
        println("hello")
    }
    //因为globalScope是整个应用程序的生命周期,不能在此手动取消它,调用抛异常 java.lang.IllegalStateException: Scope cannot be cancelled because it does not have a job
    globalScope.cancel()//不能手动取消它
    while (true);
}
package com.tiger.mykotlinapp.scope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
fun main() {
    val coroutineScope = CoroutineScope(Dispatchers.Default)
    coroutineScope.launch {
        delay(3000)
        println("hello")
    }
    coroutineScope.launch {
        delay(3000)
        println("hello")
    }
    //发现可以取消
    coroutineScope.cancel()
    while (true);
}

CoroutineScope和GlobalScope的区别

1. 作用域不同,第一个作用域是activity,第二个是全局整个应用程序

2.第一个可以取消,第二个取消会抛异常

3.一般都是用第一个,更加灵活。