TIL

7강 CoroutineScope와 CoroutineContext

fun main(): Unit = runBlocking {
  val job1 = CoroutineScope(Dispatchers.Default).launch {
    delay(1_000L)
    printWithThread("Job 1")
  }
}
fun main() {
  val job = CoroutineScope(Dispatchers.Default).launch {
    delay(1_000L)
    printWithThread("Job 1")
  }
  
  Thread.sleep(1_500L) // job이 새 스레드에서 루트 코루틴으로 실행되기에 기다려야 Job1이 출력될 것이다.
}

CoroutineScope와 CoroutineContext 주요 역할

public interface CoroutineScope {
  public val coroutineContext: CoroutineContext
}

코루틴의 Structured Concurrency 기반

image

  1. 부모 코루틴이 최초 CoroutineScope에서 생성된다.
  2. 자식 코루틴이 생성되면 같은 영역에서 생성되고 부모의 context에서 필요한 정보를 덮어 써 새로운 자신의 context를 만든다.
    1. 이 과정에서 부모-자식 관계도 설정한다.

클래스 내부에서 독립적인 CoroutineScope를 관리

class AsyncLogic {
  private val scope = CoroutineScope(Dispatchers.Default)
  
  fun doSomething() {
    scope.launch {
      // 어떤 작업을 수행
    }
  }
  
  fun destroy() {
    scope.cancel()
  } 
}
val asyncLogic = AsyncLogic()
asyncLogic.doSomething()

asyncLogic.destory() // 필요 없어지면 모두 정리

CoroutineContext

fun main() {
  // 각각이 Element이다.
  CoroutineName("나만의 코루틴") + Dispatchers.Default
  
  // context 자체에 Element를 추가할 수도 있다.
  coroutineContext + CoroutineName("나만의 코루틴")
  
  // Element를 제거할 수도 있다.
  coroutineContext.minusKey(CoroutineName.key)
}

CoroutineDispatcher

fun main() {
  val threadPool = Executors.newSingleThreadExecutor()
  CoroutineScope(threadPool.asCoroutineDispatcher()).launch {
    printwithThread("새로운 코루틴")
  }
}