launch
/ async
는 CoroutineScope
의 확장 함수다.runBlocking
로 코루틴 스코프를 열면 CoroutineScope
를 제공해줬던 것// `runBlocking` 을 사용하지 않았기 때문에 main 함수를 `suspend fun` 으로 만들어서 코루틴을 실행하게 함
suspend fun main() {
val job = CoroutineScope(Dispatchers.Default).launch {
delay(1000L)
println("Job 1")
}
job.join();
}
CoroutineContext
의 데이터를 보관하는 것class AsyncLogic {
private val scope = CoroutineScope(Dispatchers.Default)
fun doSomething() {
scope.launch {
// .. 무언가의 코루틴 작업
}
}
fun destory() {
scope.cancel()
}
}
CoroutineContext
는 인터페이스public interface CoroutineScope {
public val coroutineContext: CoroutineContext
}
CoroutineExceptionHandler
, 코루틴 그 자체, CoroutineDispatcher
등CoroutineScope: 코루틴이 탄생할 수 있는 영역
CoroutineContext: 코루틴과 관련된 데이터를 보관
새로운 자식 코루틴이 만들어질 떄
graph TD; subgraph CoroutineScope A[부모 코루틴] --> B[자식 코루틴] A --> C[Context] B --> D[Context] C .->|복사| D C --> E[이름] C --> F[Dispatchers.Default] D --> G[새로운 이름] D --> H[Dispatchers.Default] end style A fill:#ffcc00,stroke:#333,stroke-width:2px; style B fill:#ff6666,stroke:#333,stroke-width:2px; style C fill:#ffcc00,stroke:#333,stroke-width:2px; style D fill:#ff6666,stroke:#333,stroke-width:2px; style E fill:#fff,stroke:#333,stroke-width:2px; style F fill:#fff,stroke:#333,stroke-width:2px; style G fill:#fff,stroke:#333,stroke-width:2px; style H fill:#fff,stroke:#333,stroke-width:2px;
- CoroutineScope: 모든 코루틴은
CoroutineScope
내에서 실행됩니다. 이 스코프는 코루틴의 생명 주기를 관리합니다.- 부모 코루틴:
CoroutineScope
에서 생성된 첫 번째 코루틴이 부모 코루틴이 됩니다.
- Context: 부모 코루틴은 자신만의 Context를 가집니다. 이 Context에는 코루틴의 이름과
Dispatchers.Default
가 포함됩니다.- 이름: 부모 코루틴의 Context에 설정된 이름입니다.
- Dispatchers.Default: 부모 코루틴이 실행될 디스패처입니다.
- 자식 코루틴: 부모 코루틴 내에서 생성된 코루틴은 자식 코루틴이 됩니다.
- Context 복사: 자식 코루틴은 부모 코루틴의 Context를 복사하여 상속받습니다. 이는 자식 코루틴이 부모 코루틴의 속성과 설정을 그대로 이어받음을 의미합니다.
- 새로운 이름: 자식 코루틴은 부모 코루틴과는 다른 새로운 이름을 가질 수 있습니다.
Map
+ Set
을 합쳐놓은 형태
suspend fun main() {
val job = CoroutineScope(Dispatchers.Default).launch {
coroutineContext + CoroutineName("새로운 코루틴 이름")
// coroutineContenxt: 현재 코루틴의 컨텍스트
// CoroutineName(str): 새로운 이름 요소를 컨텐스트로 결합
coroutineContext.minusKey(CoroutineName.Key)
// minusKey(CoroutineContext Element): 기존에 있던 요소를 제거
}
}
Dipatchers.Default
Dispatchers.IO
Dispatchers.Main
ExcutorService
를 Dispatcher
로 사용할 수도 있음
asCoroutineDispatcher()
확장 함수로 사용 가능fun main() {
val threadPool = Excutors.newSingleThreadExcutor()
CoroutineScope(threadPool.asCoroutineDispatcher()).launch {
// ...
}
}
- CoroutineScope는 코루틴이 시작되고 관리되는 스코프를 정의합니다. 이는 여러 코루틴의 생명주기를 함께 관리할 수 있게 해줍니다.
- CoroutineContext는 코루틴의 컨텍스트 정보를 담고 있습니다. 여기에는 디스패처, 이름, 예외 핸들러 등 다양한 요소가 포함될 수 있습니다.
- CoroutineScope의 주요 역할은 코루틴의 실행 범위를 제공하고, 이 범위 내에서 실행되는 모든 코루틴의 생명주기를 관리하는 것입니다.
- CoroutineContext는 코루틴의 실행 환경과 관련된 데이터를 보관하며, 각 코루틴은 자신만의 컨텍스트를 가질 수 있습니다.
CoroutineName
과 Dispatchers
를 결합할 수 있음.// Dispatchers.Default와 CoroutineName("MyCoroutine")을 결합하여 하나의 CoroutineContext를 생성
val context = Dispatchers.Default + CoroutineName("MyCoroutine")
launch
와 async
는 CoroutineScope
의 확장 함수로, 이 스코프 내에서 새로운 코루틴을 시작할 수 있음.