KEEP

https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md

Use cases

Coroutine은 suspendable computation이다. some point에서 suspend되었다가 (다른 쓰레드에서도) resume 될 수 있다. Coroutine은 상호 호출이 가능해서 협력적인 멀티태스킹이 가능하다.

Asynchronous computations

Callback Hell. 람다를 이용해서 코드는 깔끔하게 나오지만 indent가 계속 되는 걸 막을 수는 없다.

코루틴으로 하면 간단하게(straightforward) 나옴.

launch {
    // suspend while asynchronously reading
    val bytesRead = inChannel.aRead(buf) 
    // we only get to this line when reading completes
    ...
    ...
    process(buf, bytesRead)
    // suspend while asynchronously writing   
    outChannel.aWrite(buf)
    // we only get to this line when writing completes  
    ...
    ...
    outFile.close()
}

aRead(), aWrite()는 suspending function. suspend execution 했다가(근데 블록킹하지 않음), 콜이 완료되면 resume.

launch coroutine builder.

aRead aWrite suspending functions로 continuation을 implicitly 받는다.

continuation generic callbacks

<aside> 💡 implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2") // build.gradle에 추가

launch는 CoroutineScope의 확장함수인데, CS는 인터페이스이다. 따라서 쓰려면 GlobalScope.launch 같은 구체 클래스를 가져다 써야 한다.

</aside>

Futures

future(aka promise, deferred)를 이용하는 방식도 가능

val future = future {
    val original = loadImageAsync("...original...") // creates a Future
    val overlay = loadImageAsync("...overlay...")   // creates a Future
    ...
    // suspend while awaiting the loading of the images
    // then run `applyOverlay(...)` when they are both loaded
    applyOverlay(original.await(), overlay.await())
}

Generators

Lazily computed sequences.

val fibonacci = sequence {
    yield(1) // first Fibonacci number
    var cur = 1
    var next = 1
    while (true) {
        yield(next) // next Fibonacci number
        val tmp = cur + next
        cur = next
        next = tmp
    }
}