ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • withContext
    BackEnd/coroutine 2025. 6. 14. 11:00
    반응형

    withContext 함수

    • withContext 함수는 인자로 받은 CoroutineDispatcher를 사용해 코루틴의 실행 스레드를 전환하고, 람다식의 코드를 실행한 후 결과값을 반환하는 함수입니다. 람다식을 실행한 후에는 스레드가 다시 이전의 Dispatcher을 사용하도록 전환됩니다.
    • withContext를 사용하면 코루틴이 생성되지 않습니다.
    import kotlinx.coroutines.*
    
    fun main() = runBlocking<Unit> {
        val result: String = withContext(Dispatchers.IO) {
            delay(1000L) // 네트워크 요청
            println("[${Thread.currentThread().name}] 결과값이 반환됩니다")
            return@withContext "결과값" // 결과값 반환
        }
        println("[${Thread.currentThread().name}] $result") // 결과값 출력
    }

     

    withContext vs async-await

    • async-await이 연속으로 호출되는 동작을 withContext로 대체 가능합니다.
    import kotlinx.coroutines.*
    
    fun main() = runBlocking<Unit> {
        val result: String = async(Dispatchers.IO) {
            delay(1000L) // 네트워크 요청
            println("[${Thread.currentThread().name}] 결과값이 반환됩니다")
            "결과값" // 결과값 반환
        }.await()
        println("[${Thread.currentThread().name}] $result") // 결과값 출력
    }

     

    withContext 주의점

      다음과 같이 병렬 처리를 위해 withContext를 사용하면 안됩니다. withContext는 코루틴이 유지된 상태로 스레드만 바뀌기 때문에 순차 처리됩니다. 다음 코드의 경우, 약 2초가 걸립니다.

    import kotlinx.coroutines.*
    
    fun main() = runBlocking<Unit> {
        val result1: String = withContext(Dispatchers.IO) {
            delay(1000L) // 네트워크 요청
            "결과값1" // 결과값 반환
        }
        val result2: String = withContext(Dispatchers.IO) {
            delay(1000L) // 네트워크 요청
            "결과값1" // 결과값 반환
        }
    
        val results = listOf(result1, result2)
        println("[${Thread.currentThread().name}] ${results.joinToString(", ")}") // 결과값 출력
    }

     

      병렬 처리를 위해서는 다음과 같이 async 함수를 사용해야 합니다.

    import kotlinx.coroutines.*
    
    fun main() = runBlocking<Unit> {
        val networkDeferred1: Deferred<String> = async(Dispatchers.IO) {
            delay(1000L) // 네트워크 요청
            "결과값1" // 결과값 반환
        }
        val networkDeferred2: Deferred<String> = async(Dispatchers.IO) {
            delay(1000L) // 네트워크 요청
            "결과값2" // 결과값 반환
        }
    
        val results: List<String> = awaitAll(networkDeferred1, networkDeferred2)
        println("[${Thread.currentThread().name}] ${results.joinToString(", ")}") // 결과값 출력
    }

     

    반응형

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

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

    댓글

Designed by Tistory.