새 코루틴의 범위를 정의한다.
코루틴을 생성하기 위한 명세서이다.
모든 코루틴 빌더(예: launch
, async
등)는 코루틴 스코프의 확장이며, 코루틴 컨텍스트를 상속받아 모든 요소와 취소를 자동으로 전파한다.
public fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job {
// 기존의 컨텍스트와 합쳐진 새로운 컨텍스트
val newContext = newCoroutineContext(context)
// 새로운 컨텍스트로 만들어진 코루틴
val coroutine = if (start.isLazy)
LazyStandaloneCoroutine(newContext, block) else
StandaloneCoroutine(newContext, active = true)
coroutine.start(start, coroutine, block)
return coroutine
}
@ExperimentalCoroutinesApi
public actual fun CoroutineScope.newCoroutineContext(context: CoroutineContext): CoroutineContext {
// 기존의 coroutineContext와 파라미터로 전달 받은 context를 합친다.
val combined = foldCopies(coroutineContext, context, true)
val debug = if (DEBUG) combined + CoroutineId(COROUTINE_ID.incrementAndGet()) else combined
return if (combined !== Dispatchers.Default && combined[ContinuationInterceptor] == null)
debug + Dispatchers.Default else debug
}
CoroutineScope()
및 MainScope()
는 범위의 독립형 인스턴스를 얻는 가장 좋은 방법으로 코루틴이 더 이상 필요 없을 때 코루틴 범위를 취소한다.
더하기 연산자를 사용하여 추가 컨텍스트 요소(CoroutineContext.Element
)를 스코프에 추가할 수 있다.
그렇게 추가된 context를 파라미터를 통해 전달 받을 수 있기 때문에 '코루틴 컨텍스트를 상속받아 모든 요소와 취소를 자동으로 전파' 할 수 있다.
추가로 코루틴 객체 Job
은 CoroutineContext.Element
을 확장하고 있다.
public interface Job : CoroutineContext.Element {
// ...
}