ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • CoroutineContext
    BackEnd/coroutine 2025. 6. 15. 07:00
    반응형

    CoroutineContext 구성요소

    • CoroutineName: 코루틴의 이름 설정에 사용되는 객체입니다.
    • CoroutineDispatcher: 코루틴을 스레드에 보내서 실행하는 객체입니다.
    • Job: 코루틴을 조작하는데 사용되는 객체입니다.
    • CoroutineExceptionHandler: 코루틴에서 발생된 예외를 처리하는 객체입니다.

     

    CoroutineContext 구성요소를 관리하는 방법

    • CoroutineContext 객체는 구성요소에 대한 키-값 쌍으로 구성요소를 관리합니다.
    • 각 구성요소는 고유한 키를 가지며, 키에 대해 중복된 값은 허용되지 않습니다.
    • CoroutineContext 객체에 구성 요소를 추가하기 위해서는 더하기 연산자(+)를 사용하면 됩니다. CoroutineContext 객체는 키에 값을 직접 대입하는 방법을 사용하지 않습니다.
    val coroutineContext = newSingleThreadContext("MyThread") + CoroutineName("MyCoroutine")
    Key Value
    CoroutineName Key CoroutineName("MyCoroutine")
    CoroutineDispatcher Key newSingleThreadContext("MyThread")
    Job Key 설정되지 않음
    CoroutineExceptionHandler Key 설정되지 않음

     

    • CoroutineContext 객체에 같은 구성요소가 둘 이상 더해지면, 나중에 추가된 구성요소가 이전 값을 덮어씌웁니다.
    • 여러 구성요소로 이뤄진 CoroutineContext 두개가 합쳐질 때도 같은 키를 가진 구성요소가 있다면, 나중에 들어온 구성요소가 먼저 들어온 구성요소를 덮어 씌웁니다.
    val coroutineContext = newSingleThreadContext("MyThread") + CoroutineName("MyCoroutine")
    val newCoroutineContext = coroutineContext + CoroutineName("NewCoroutine")
    Key Value
    CoroutineName Key CoroutineName("NewCoroutine")
    CoroutineDispatcher Key newSingleThreadContext("MyThread")
    Job Key 설정되지 않음
    CoroutineExceptionHandler Key 설정되지 않음

     

    CoroutineContext 구성요소의 키

    • CoroutineContext 구성요소에 접근하기 위해서는 구성요소가 가진 고유한 키가 필요합니다.
    • CoroutineContext 구성요소의 키는 CoroutineContext.Key 인터페이스를 구현해 만들어집니다.
    • CoroutineContext 구성요소는 보통 CoroutineContext.Key를 자신의 내부에 싱글톤 객체로 구현합니다.
    CoroutineContext 구성요소 Key
    CoroutineName CoroutineName.Key
    CoroutineDispatcher CoroutineDispatcher.Key
    Job Job.Key
    CoroutineExceptionHandler CoroutineExceptionHandler.Key

     

      CoroutineContext의 구성요소에 접근하기 위해서는 get 함수의 인자로 Key를 넘기면 됩니다. get 함수는 연산자 함수로 선언되어 있어서 대괄호 '[]'로 대체 가능합니다.

    import kotlinx.coroutines.*
    
    fun main() = runBlocking<Unit> {
      val coroutineContext = CoroutineName("MyCoroutine") + Dispatchers.IO
      val nameFromContext = coroutineContext[CoroutineName.Key]
      println(nameFromContext)
    }

     

      CoroutineName, Job, CoroutineDispatcher, CoroutineExceptionHandler는 동반 객체로 CoroutineContext.Key를 구현하는 Key를 가져서 '.Key'를 쓰지 않고도 구성요소에 접근 가능합니다.

      단, CoroutineDispatcher을 키로 사용해 구성요소에 접근하면, 실행은 가능하지만 경고 메시지가 발생합니다. 이유는 CoroutineDispatcher.Key가 아직 Experimental API이기 때문입니다. 다음과 같이 OptIn 애노테이션을 붙이면 경고가 사라집니다.

    import kotlinx.coroutines.*
    
    @OptIn(ExperimentalStdlibApi::class)
    fun main() = runBlocking<Unit> {
      val coroutineContext = CoroutineName("MyCoroutine") + Dispatchers.IO
      val nameFromContext = coroutineContext[CoroutineDispatcher] // '.Key'제거
      println(nameFromContext)
    }

     

    안정화된 API

    • 구성요소 인스턴스는 모두 key 프로퍼티를 가집니다. 이를 사용해 싱글톤 Key에 접근할 수 있습니다.
    import kotlinx.coroutines.*
    
    fun main() = runBlocking<Unit> {
      val coroutineName : CoroutineName = CoroutineName("MyCoroutine")
      val dispatcher : CoroutineDispatcher = Dispatchers.IO
      val coroutineContext = coroutineName + dispatcher
    
      println(coroutineContext[coroutineName.key])
      println(coroutineContext[dispatcher.key])
    }

     

    CoroutineContext 구성요소 제거하기

    • CoroutineContext 객체에서 특정 구성요소를 제거하기 위해서는 minusKey 함수를 호출하고, 구성요소의 키를 넘기면 됩니다.
    • minusKey 함수 사용 시 minusKey 함수를 호출한 CoroutineContext 객체는 그대로 유지되고 구성요소가 제거된 새로운 CoroutineContext 객체가 반환됩니다.
    import kotlinx.coroutines.*
    import kotlin.coroutines.CoroutineContext
    
    fun main() = runBlocking<Unit> {
      val coroutineName = CoroutineName("MyCoroutine")
      val dispatcher = Dispatchers.IO
      val myJob = Job()
      val coroutineContext: CoroutineContext = coroutineName + dispatcher + myJob
    
      val deletedCoroutineContext = coroutineContext.minusKey(CoroutineName)
    
      println(deletedCoroutineContext)
    }

     

    반응형

    'BackEnd > coroutine' 카테고리의 다른 글

    withContext  (0) 2025.06.14
    async-await  (0) 2025.06.08
    Coroutine 상태  (1) 2025.06.07
    Coroutine 취소  (0) 2025.06.01
    지연 Coroutine  (0) 2025.05.31

    댓글

Designed by Tistory.