Skip to content

CoroutineBuilder #5

Description

@daehwan2da

suspending function 들은 Continuation 을 서로간에 주고받으며 동작한다.

  • coroutine function 에서는 normal function 호출이 가능하나, normal function 에서는 suspend function call 이 불가하다.
    • 어디선가는 coroutine 을 시작해주어야한다.
    • CoroutineBuilder 를 통해 coroutine 을 시작할 수 있다.

Explore the three essential coroutine builders provided by kotlinx.coroutine library

  • launch
  • async
  • runBlocking

launch

새로운 쓰레드를 시작하는 컨셉으로 동작한다. 코루틴을 시작하면, 독립적으로 동작하게된다.

  • launch 는 CoroutineScope 의 extension function 으로 CoroutineScope 내부에서만 호출이 가능하다.
fun CoroutineScope.launch (
  context: CoroutineContext = EmptyCoroutineContext,
  start : CoroutineStart = CoroutineStart.DEFAULT,
  block: suspend CoroutineScope.() -> T
) : Job

runBlocking

  • The general rule is that coroutine should never block threads. only suspend them.
    • 하지만, blocking 이 필요한 시점들이 존재한다.
      • main function
      • unit test
fun <T> runBlocking(
  context: CoroutineContext = EmptyCoroutineContext,
  block: suspend CoroutineScope.() -> T
) : T

Q. 왜 runBlocking 은 launch, async 와 달리 독립적으로 호출이되며 사용이 가능할까?

  • launch 와 async 는 CoroutineScope 의 확장함수여서 CoroutineScope 범위 안에서만 호출이 가능하다.

async

async builder 는 launch builder 와 비슷하지만, value 를 제공하기위해 설계되었다.
Deferred<T>를 응답한다.

  • async 는 CoroutineScope 의 extension function 으로 CoroutineScope 내부에서만 호출이 가능하다.
fun CoroutineScope.async(
  context: CoroutineContext = EmptyCoroutineContext,
  start : CoroutineStart = CoroutineStart.DEFAULT,
  block : suspend CoroutineScope.() -> T
) : Deferred<T>

Structured Concurrency

As parent might recoginize, a parental responsibility is to wait for all their children.
부모 coroutine 은 자식 coroutine 에 Scope 를 제공하며, 자식들은 해당 Scope 내에서 호출되어진다. -> Structured Concurrency

  • Most important effects of the parent-child relationship
    • 자식은 부모의 context 를 상속받는다. CoroutineContext
    • 부모는 모든 자식이 종료될때까지 suspend 처리된다. (Job, children awaiting)
    • 부모가 Cancel 처리되면, 자식도 Cancel 처리된다. (Cancellation)
    • 자식에서 Error 가 발생하면, 부모역시 영향을 받아 destroy 된다. (Exception Handling)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions