Kotlin/포스팅

코루틴 흐름 제어

짜집퍼박사(짜박) 2024. 1. 9. 15:51

코루틴의 흐름 제어는 비동기 코드의 순차적 실행을 보장하고, 여러 코루틴 간에 데이터를 전달하고 결합하는 등의 작업을 가능하게 합니다. 이를 위해 여러 함수와 패턴이 제공되며, 아래에서 주요한 흐름 제어에 대해 알아보겠습니다.

 

1. 코루틴 빌더

코루틴은 launch, async, runBlocking 등의 빌더 함수를 사용하여 생성됩니다. 이들 빌더 함수는 코루틴의 시작과 실행을 담당하며, 각각의 특징에 따라 사용됩니다.

launch: 비동기적으로 실행되는 코루틴을 시작하고 반환값이 없습니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        // 비동기 작업
        delay(1000)
        println("Coroutine is running.")
    }

    println("Main thread is not blocked.")
    delay(2000)
    println("End")
}

async: 비동기적으로 실행되는 코루틴을 시작하고 값을 반환할 수 있습니다. await 함수를 통해 해당 값을 기다릴 수 있습니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferred = async {
        // 비동기 작업
        delay(1000)
        "Result"
    }

    println("Main thread is not blocked.")
    val result = deferred.await()
    println("Result: $result")
}

runBlocking: 현재 스레드를 차단하면서 블록 내에서 코루틴을 실행합니다. 주로 테스트 코드나 메인 함수에서 사용됩니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        // 비동기 작업
        delay(1000)
        println("Coroutine is running.")
    }

    println("Main thread is blocked until coroutine is done.")
}

 

2. CoroutineScope

coroutineScope 함수를 사용하여 현재 코루틴 범위 내에서 새로운 코루틴을 실행할 수 있습니다. coroutineScope 블록 내의 모든 코루틴이 완료될 때까지 현재 스레드는 차단되지 않습니다.

import kotlinx.coroutines.*

suspend fun mySuspendingFunction() {
    coroutineScope {
        // 비동기 작업
        delay(1000)
        println("Coroutine is running.")
    }
}

fun main() = runBlocking {
    launch {
        mySuspendingFunction()
    }

    println("Main thread is not blocked.")
    delay(2000)
    println("End")
}

 

3. 취소와 예외 처리

코루틴은 cancel 함수를 사용하여 취소되거나, 예외를 통해 종료될 수 있습니다. 또한 try, catch, finally 등을 사용하여 예외를 처리할 수 있습니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            // 비동기 작업
            delay(1000)
            throw RuntimeException("An error occurred")
        } catch (e: Exception) {
            println("Caught an exception: ${e.message}")
        } finally {
            println("Finally block")
        }
    }

    delay(500)
    job.cancel() // 코루틴을 취소하고 예외 발생
    job.join() // 코루틴이 완료될 때까지 대기

    println("End")
}

 

4. 데이터 흐름 제어

async와 await를 사용하여 여러 코루틴 간에 데이터를 비동기적으로 전달하고 조합할 수 있습니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferred1 = async {
        delay(1000)
        "Hello"
    }

    val deferred2 = async {
        delay(1000)
        "World"
    }

    val combined = "${deferred1.await()}, ${deferred2.await()}"
    println(combined)
}

코루틴을 통해 비동기 코드의 순차적 실행과 데이터 흐름을 간결하게 제어할 수 있습니다. 특히 async와 await를 사용하여 여러 코루틴 간에 데이터를 쉽게 전달하고 결합할 수 있습니다.

 

With ChatGPT

'Kotlin > 포스팅' 카테고리의 다른 글

코루틴 취소  (0) 2024.01.09
코루틴 잡 생명 주기  (0) 2024.01.09
코루틴 문맥  (0) 2024.01.07
코루틴 구조적 동시성  (0) 2024.01.07
코루틴 영역  (0) 2024.01.07