KotlinConf 2017 - Introduction to Coroutines by Roman Elizarov

CmplxN·2021년 1월 12일
0
post-thumbnail

Asynchronous Programming

  • Callbacks : 코드가 매우 복잡해짐. 콜백지옥. 예외처리 쉽지 않다.
  • Rx/Promises/Futures : Compose하는 형식, 예외처리도 더 좋음(propagation). 아예 새로운 프로그래밍 방식을 학습해야함.
  • Coroutines : 직관적인 코드로 목적을 달성할 수 있음. suspend등 몇가지 키워드만 붙이면 일반적인 코드(H/O, try/catch, loops...)랑 완전 같음. (looks natural)

Suspending Functions

  • thread를 block하지 않고, suspend function을 호출 한 부분에서 suspend했다가 작업이 완료되면 돌아올 수 있다.

Coroutine Builders

  • suspend function을 쓸 수 있는 세계를 build
  • launch
public fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job

Async

  • C# async & await
  • async(a coroutine builder, not a keyword), await(function), Deferred(Future)

Coroutines?

  • Light-weight Thread
  • 10만번 1초 정지후 점찍기(println('.'))
    • Thread : OOM (heavy)
    • Coroutines : No Error (light-weight)
fun main(): Unit = runBlocking {
    val jobs = List(100000) {
        launch {
            delay(1000L)
            print('.')
        }
    }
    jobs.forEach { it.join() }
}

Java Interop

  • future coroutine builder

Beyond asynchronous code

  • 피보나치 수열
fun <T> sequence(@BuilderInference block: suspend SequenceScope<T>.() -> Unit): Sequence<T>

// runs synchronous with invoker?
val fibonacci = sequence {
    var cur = 1
    var next = 1
    while (true) {
        yield(cur)
        val temp = cur + next
        cur = next
        next = temp
    }
}

val iter = fibonacci.iterator()
println(iter.next())

어제 봤던 영상과 비슷한 내용이 어느정도 있었다.
아직은 뜬구름 잡는 느낌이 없지는 않다.
이해력 부족

profile
Android Developer

0개의 댓글