티스토리 뷰

Coroutine Builder

CoroutineScope의 확장함수로 Coroutine을 만드는 역할을 합니다.

CoroutineScope(Dispatchers.IO).launch {
    // do something coroutine
}

 

launch()

가장 기본적인 Builder입니다. launch()는 Thread를 Blocking하지 않으며Job이라는 객체를 반환합니다. Job은 cancel(), join() 등 의 함수를 가지고 있습니다.

launch의 2번때 매개변수로 CoroutineStart가 주어집니다. CoroutineStart으로 시작 방식을 지정할 수 있습니다.

fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext, 
    start: CoroutineStart = CoroutineStart.DEFAULT, 
    block: suspend CoroutineScope.() -> Unit
): Job
CoroutineStart
- DEFAULT : CoroutineContext에 따라 즉시 실행합니다. 시작할 기회를 얻기 전에 취소되면 취소한다. (기본값)
- LAZY : start() 함수로 직접 시작합니다.
- ATOMIC : DEFAULT와 비슷하지만 시작할 기회를 얻기 전에 취소되어도 시작하고, suspend될 때 취소된다.
-UNDISPATCHED : 현재 Thread에서 바로 시작하고 suspend 되었다가 resume될 때 Coroutine Context에 의해 실행된다.

 

async()

launch()와 다르게 결과 값이 존재합니다. Deferred가 반환되고 await()를 통해 결과를 받아올 수 있습니다. 또한 Deferred는 Job을 상속 받고 있기 때문에 cancel(), join() 등 함수를 사용할 수 있습니다.

launch()와 마찬가지로 2번째 매개변수로 CoroutineStart를 받습니다.

public fun <T> CoroutineScope.async(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T> {
    val newContext = newCoroutineContext(context)
    val coroutine = if (start.isLazy)
        LazyDeferredCoroutine(newContext, block) else
        DeferredCoroutine<T>(newContext, active = true)
    coroutine.start(start, coroutine, block)
    return coroutine
}
public interface Deferred<out T> : Job {
    public suspend fun await(): T

    public val onAwait: SelectClause1<T>

    @ExperimentalCoroutinesApi
    public fun getCompleted(): T

    public fun getCompletionExceptionOrNull(): Throwable?
}

 

withContext

코루틴안에서 CoroutineContext 전환에 최적화된 Builder이다. 아래 예시처럼 Coroutine 내에서 동기처리할 때 withContext를 통해 쉽게 처리할 수 있다. withContext의 장점은 하나의 Coroutine에서 Thread를 Block하지 않고 서로 다른 Thread를 사용할 수 있다는 점이다. withContext가 호출될 때 해당 Coroutine은 suspend되며 withContext는 해당 Context에 맞게 작업을 진행후 결과를 반환하고 다시 해당 Coroutine은 resume된다.

CoroutineScope(Dispatchers.Main).launch {
    val deferred = async(Dispatchers.IO) {
        // Something Dispatchers.IO
    }

    val result = deferred.await()
}

CoroutineScope(Dispatchers.Main).launch {
    val result = withContext(Dispatchers.IO) {
        // Something Dispatchers.IO
    }
}

 

runBlocking

새로운 Coroutine을 만들고 해당 Coroutine이 완료될 때까지 Thread를 Blocking한다. 사용할 때 주의해야 하며 Coroutine 내부에서 runBlocking을 사용하는 것은 바람직하지 않다. runBlocking이 종료되면 결과값을 반환한다.

'Android > Coroutine' 카테고리의 다른 글

Android Coroutine - Job Lifecycle  (0) 2022.01.15
Android Coroutine - Cancel  (0) 2022.01.08
Android Coroutine - CoroutineContext  (0) 2022.01.07
Android Coroutine - Scope  (0) 2022.01.07
Android Coroutine - 개념  (0) 2022.01.04
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함