Launch

2024. 11. 27. 14:15Kotlin

코틀린(Kotlin)에서 launch는 코루틴을 시작하는 가장 기본적인 방법 중 하나입니다. launchJob 객체를 반환하며, 비동기적으로 작업을 수행하지만 결과를 반환하지 않습니다. 이는 주로 실행할 작업이 결과를 반환할 필요가 없고, 단순히 비동기적으로 수행되어야 할 때 사용됩니다.

launch의 기본 사용법

launchCoroutineScope 내에서 호출되어야 합니다. 가장 일반적인 방법은 runBlocking을 사용하여 최상위 코루틴을 시작하는 것입니다:

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        // 코루틴 블록 내에서 실행될 코드
        delay(1000L)
        println("Hello from Coroutine!")
    }
    println("Hello from Main!")
}

위 예제에서 launch 블록은 비동기적으로 실행되며, delay(1000L)로 1초 동안 일시 중단됩니다. 그 동안 println("Hello from Main!")은 즉시 실행됩니다.

launch와 CoroutineScope

launchCoroutineScope 내에서 호출되어야 합니다. runBlocking, launch, async 등은 모두 CoroutineScope를 생성합니다. 다음은 CoroutineScope를 명시적으로 사용하는 예제입니다:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val scope = CoroutineScope(Dispatchers.Default)

    scope.launch {
        delay(1000L)
        println("Hello from Coroutine!")
    }

    println("Hello from Main!")
}

launch와 Dispatchers

launchDispatchers를 사용하여 코루틴이 실행될 스레드 또는 스레드 풀을 지정할 수 있습니다. 다음은 다양한 Dispatchers를 사용하는 예제입니다:

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch(Dispatchers.Default) {
        println("Running on Default: ${Thread.currentThread().name}")
    }

    launch(Dispatchers.IO) {
        println("Running on IO: ${Thread.currentThread().name}")
    }

    launch(Dispatchers.Unconfined) {
        println("Running on Unconfined: ${Thread.currentThread().name}")
    }

    // Dispatchers.Main은 안드로이드 환경에서만 사용 가능
    // launch(Dispatchers.Main) {
    //     println("Running on Main: ${Thread.currentThread().name}")
    // }
}

Job 객체

launchJob 객체를 반환합니다. Job 객체를 사용하여 코루틴을 제어할 수 있습니다. 예를 들어, 코루틴을 취소하거나 완료 여부를 확인할 수 있습니다:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job: Job = launch {
        delay(1000L)
        println("Hello from Coroutine!")
    }

    println("Job is active: ${job.isActive}")
    job.join()  // Wait for the coroutine to complete
    println("Job is completed: ${job.isCompleted}")
}

예외 처리

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

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            throw Exception("Something went wrong")
        } catch (e: Exception) {
            println("Caught exception: ${e.message}")
        }
    }
    job.join()
}

구조적 동시성

코루틴은 구조적 동시성을 지원하며, 이는 부모 코루틴이 완료될 때 자식 코루틴도 함께 취소됨을 의미합니다. launch도 이 원칙을 따릅니다:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val parentJob = launch {
        val childJob = launch {
            delay(1000L)
            println("Hello from Child Coroutine!")
        }
        delay(500L)
        println("Hello from Parent Coroutine!")
    }
    delay(300L)
    parentJob.cancel()  // Cancels the parent job and its children
}

위 예제에서 parentJob.cancel()을 호출하면 부모 코루틴과 그 안의 자식 코루틴이 모두 취소됩니다.

'Kotlin' 카테고리의 다른 글

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