daehwan2yo / dig-up-kotlin

1 stars 0 forks source link

coroutine with kotlin #20

Open daehwan2yo opened 1 year ago

daehwan2yo commented 1 year ago

Maintaining a blocked thread is always costly, while maintaining a suspended coroutine is almost free.

Why we use runBlocking() for test coroutines?

일반적으로 코루틴은 쓰레드를 block 하지 않지만, main thread 가 너무 일찍 종료되어 코루틴을 동작하지 못해 blocking 이 필요한 경우가 있다. 이런 경우 runBlocking builder 를 통해 코루틴 동작을 위해 thread 를 block 시킨다.

daehwan2yo commented 1 year ago

GlobalScope

CoroutineScope

interface CoroutineScope Defines a scope for new coroutines. Every Coroutine Builder (like launch(), async) is an extension on CoroutineScope.

daehwan2yo commented 1 year ago

Coroutine Builder

reference

Builders.common.kt

CoroutineScope.launch

Launches a new coroutine without blocking the current thread and returns a reference to the coroutine as a Job.

- CoroutineScope 로 부터 파생되어진 coroutine context 를 반환한다. (Job)
- 별도의 Dispatcher 가 명시되어지지 않았다면, Dispatchers.Default 가 default 로 사용되어진다.

CoroutineScope interface 의 확장함수

coroutine 테스트를 하면서 왜 항상 main 에서 Thread.sleep() (or deplay() ) 를 호출해주어야할까?

main thread 가 코루틴을 호출하자마자 종료되어진다. main thread 가 종료됨에 따라서 해당 쓰레드의 코루틴들은 job 을 수행하지 못하게되어진다.

<T> CoroutineScope.async

<T> withContext