Android/Coroutine

[코루틴 기초] CoroutineScope (=코루틴 영역, 코루틴 스코프)

네모메모 2022. 7. 8. 21:06
반응형

 

 

CoroutineScope

: (코루틴의 라이프사이클을 시작하고 제어하기 위해 생성되는) 코루틴 지정 범위

ㄴ>  Ex) CoroutineScope가 전역 역역(global scope)인 경우(= 코루틴의 전역 영역에서 실행된 경우),
           -> 코루틴의 생명주기가 전체 어플리케이션의 생명주기에 의해서만 제약되는 영역이 된다.

 

 

- (CoroutineScope의 확장 함수인) 'launch' 또는 'async'를 사용하여 코루틴 실행 및 생성한 모든 코루틴을 추적함

   cf) 디스패처와 달리 CoroutineScope 코루틴을 실행하지 않는다.

더보기

BuildersKt.class

public fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job {
    ...
}


public fun <T> CoroutineScope.async(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T> {
    ...
}

 

 

 

- 실행 중인 코루틴은 언제든지 cancel()을 호출하여 취소가능

class ExampleClass {

    // Job and Dispatcher are combined into a CoroutineContext which
    // will be discussed shortly
    val scope = CoroutineScope(Job() + Dispatchers.Main)

    fun exampleMethod() {
        // Starts a new coroutine within the scope
        scope.launch {
            // New coroutine that can call suspend functions
            fetchDocs()
        }
    }

    fun cleanUp() {
        // Cancel the scope to cancel ongoing coroutines work
        scope.cancel()
    }
}

 

- CoroutineScope 생성 시, 생성자에 대한 매개 변수로 CoroutineContext를  전달한다.

 

 


 

 

대표적인 코루틴 실행 함수들

1. launch { .. } 

- 코루틴 빌더

public fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job

 

 

2. async { .. } 

- 코루틴 빌더

public fun <T> CoroutineScope.async(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T> 

 

 

3. coroutineScope { .. } 

- 자식 스레드가 완료될 때 까지 현재 스레드를 block 시키지 않는다. cf) runBlocking {..}

public suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R 

 

 

4. runBlocking { .. } 

- 자식 스레드가 완료될 때 까지 현재 스레드를 block 시킨다.

@Throws(InterruptedException::class)
public actual fun <T> runBlocking(context: CoroutineContext, block: suspend CoroutineScope.() -> T): T 

 

 


 

Android CoroutineScope

-  Android에서 일부 KTX 라이브러리특정 수명 주기 클래스에 자체 CoroutineScope를 제공합니다. 

 

1. ViewModel에는 viewModelScope

     (ViewModel 클래스는 ViewModel의 onCleared() 메서드에서 자동으로 범위를 취소)

 

2.  Lifecycle에는lifecycleScope.

 

 

 


 

 


[참조]

- https://kotlinlang.org/docs/coroutines-basics.html#your-first-coroutine

- https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/

 

- https://medium.com/androiddevelopers/coroutines-first-things-first-e6187bf3bb21

반응형