여러 중단 함수를 동시에 실행하려면 각각 GlobalScope.async로 래핑해야 하지만 GlobalScope를 사용하는 방법은 선호되는 방법이 아니다.

public object GlobalScope : CoroutineScope {
    override val coroutineContext: CoroutineContext
        get() = EmptyCoroutineContext
}

GlobalScope를 보면 컨텍스트가 EmptyCoroutineContext인 것을 알 수 있다.

이 컨텍스트는 부모의 컨텍스트를 덮어쓰게 되고 다음의 문제가 발생할 수 있다.

coroutineScope

coroutineScope는 스코프를 시작하는 중단 함수이다.

public suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R

coroutineScope 특징

coroutineScope는 아래 특징을 가진다.

fun main() = runBlocking {
    val a = coroutineScope {
        delay(2000)
        10
    }
    println("a is calculated")

    val b = coroutineScope {
        delay(2000)
        20
    }
    println(a)
    println(b)
}
// (2 sec)
// a is calculated
// (2 sec)
// 10
// 20