withContext

2024. 11. 27. 15:59Kotlin

코틀린(Kotlin)에서 withContext는 코루틴의 컨텍스트를 일시적으로 변경하여 특정 블록을 실행하는 데 사용되는 함수입니다. 이는 주로 다른 디스패처(Dispatcher)에서 코드를 실행하고 싶을 때 사용됩니다. withContextsuspend 함수이기 때문에 코루틴 내에서만 호출될 수 있으며, 코루틴의 일시 중단과 재개를 처리합니다.

withContext의 기본 사용법

withContext를 사용하면 코드 블록을 지정된 디스패처에서 실행할 수 있습니다. 예를 들어, IO 작업을 Dispatchers.IO에서 실행하고, CPU 집약적인 작업을 Dispatchers.Default에서 실행할 수 있습니다.

다음은 withContext의 기본 예제입니다:

import kotlinx.coroutines.*

fun main() = runBlocking {
    println("Running in context: ${coroutineContext}")

    withContext(Dispatchers.Default) {
        println("Running in context: ${coroutineContext}")
    }

    withContext(Dispatchers.IO) {
        println("Running in context: ${coroutineContext}")
    }
}

위 예제에서 runBlocking 블록은 기본 컨텍스트에서 실행됩니다. withContext(Dispatchers.Default)withContext(Dispatchers.IO)를 사용하여 각각 다른 디스패처에서 코드 블록을 실행합니다.

withContext와 비동기 작업

withContext는 비동기 작업을 다른 디스패처에서 실행하고, 결과를 반환받을 때 유용합니다. 예를 들어, 네트워크 요청이나 파일 읽기/쓰기와 같은 IO 작업을 Dispatchers.IO에서 실행할 수 있습니다:

import kotlinx.coroutines.*

suspend fun fetchData(): String = withContext(Dispatchers.IO) {
    // Simulate a long-running IO operation
    delay(1000L)
    "Data from network"
}

fun main() = runBlocking {
    println("Fetching data...")
    val data = fetchData()
    println("Received data: $data")
}

위 예제에서 fetchData 함수는 Dispatchers.IO에서 실행되며, 1초 동안 일시 중단된 후 데이터를 반환합니다. runBlocking 블록은 fetchData 함수의 결과를 기다렸다가 출력합니다.

withContext와 예외 처리

withContext 블록 내에서 발생한 예외는 호출한 코루틴으로 전파됩니다. 예외 처리를 위해 try-catch 블록을 사용할 수 있습니다:

import kotlinx.coroutines.*

suspend fun riskyOperation(): String = withContext(Dispatchers.Default) {
    // Simulate an operation that might throw an exception
    if (Math.random() < 0.5) {
        throw Exception("Something went wrong")
    }
    "Successful operation"
}

fun main() = runBlocking {
    try {
        val result = riskyOperation()
        println("Operation result: $result")
    } catch (e: Exception) {
        println("Caught exception: ${e.message}")
    }
}

위 예제에서 riskyOperation 함수는 Dispatchers.Default에서 실행되며, 예외가 발생할 수 있습니다. runBlocking 블록 내에서 예외를 처리하여 안전하게 실행할 수 있습니다.

withContext와 구조적 동시성

withContext는 구조적 동시성을 지원합니다. 이는 부모 코루틴이 완료될 때 자식 코루틴도 함께 취소됨을 의미합니다. withContext 블록은 부모 코루틴의 구조적 동시성을 유지합니다:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        withContext(Dispatchers.Default) {
            delay(1000L)
            println("Hello from withContext!")
        }
    }
    delay(500L)
    job.cancel()  // Cancels the parent job and its children
    println("Job cancelled")
}

위 예제에서 job.cancel()을 호출하면 withContext 블록 내의 작업도 함께 취소됩니다.

'Kotlin' 카테고리의 다른 글

runBlocking  (0) 2024.11.27
Yield  (0) 2024.11.27
Launch  (0) 2024.11.27
Async  (0) 2024.11.27
Dispatchers  (0) 2024.11.27