여러 중단 함수를 동시에 실행하려면 각각 GlobalScope.async
로 래핑해야 하지만 GlobalScope
를 사용하는 방법은 선호되는 방법이 아니다.
public object GlobalScope : CoroutineScope {
override val coroutineContext: CoroutineContext
get() = EmptyCoroutineContext
}
GlobalScope
를 보면 컨텍스트가 EmptyCoroutineContext
인 것을 알 수 있다.
이 컨텍스트는 부모의 컨텍스트를 덮어쓰게 되고 다음의 문제가 발생할 수 있다.
coroutineScope
는 스코프를 시작하는 중단 함수이다.
public suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R
coroutineScope
는 아래 특징을 가진다.
async
, launch
빌더와 다르게 리시버 없이 곧바로 호출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
Job
을 오버라이딩 함