Hanbit the Developer

Kotlin Documentation | Asynchronous programming techniques 본문

Mobile/Kotlin

Kotlin Documentation | Asynchronous programming techniques

hanbikan 2023. 5. 22. 16:00

Kotlin Documentation 시리즈에 대해

Category: Concepts

문서 링크: https://kotlinlang.org/docs/async-programming.html


Threading

  • 비용이 큼
  • 제한된 개수
  • 항상 쓰레드가 available한 게 아님
  • 사용하기 어려움: 쓰레드 디버깅, race condition 등

Callbacks

fun postItem(item: Item) {
    preparePostAsync { token ->
        submitPostAsync(token, item) { post ->
            processPost(post)
        }
    }
}

fun preparePostAsync(callback: (Token) -> Unit) {
    // make request and return immediately
    // arrange callback to be invoked later
}

Futures, promises, and others

미래에 어떤 객체가 반환될 거라고 약속한다.

fun postItem(item: Item) {
    preparePostAsync()
        .thenCompose { token ->
            submitPostAsync(token, item)
        }
        .thenAccept { post ->
            processPost(post)
        }

}

fun preparePostAsync(): Promise<Token> {
    // makes request and returns a promise that is completed later
    return promise
}

Reactive extensions

Futures와 비슷하지만, Rx는 stream을 반환한다. 여러 플랫폼(C#, Java, JavaScript, …)에 대해서 일관된 API를 구성할 수 있다. 더불어 에러 핸들링에서도 더 좋은 접근법을 도입한다.

Coroutines

suspend fun과 함께 쓰이며, 계산 도중에 정지하고 다른 작업을 마친 뒤 재개할 수 있는 특징이 있어 CPU의 유휴 시간을 최소화할 수 있다.

fun postItem(item: Item) {
    launch {
        val token = preparePost()
        val post = submitPost(token, item)
        processPost(post)
    }
}

suspend fun preparePost(): Token {
    // makes a request and suspends the coroutine
    return suspendCoroutine { /* ... */ }
}