LoginSignup
5
13

More than 5 years have passed since last update.

Kotlin 1.3 Coroutine async/await 完了処理に修正が必要

Last updated at Posted at 2018-11-04

Android Studio 3.2.1

Kotlin 1.3 になって、やっとCoroutine(コルーチン)が正式版になりました。それはいいのですが、Kotlin 1.2 で快適に動いていたCoroutineの非同期完了待ち処理が1.3になってコンパイルエラーになり、驚きました。以下の修正が必要でした。

Kotlin 1.2

private fun asyncPlus1(value: Int): Deferred<Int> = async(CommonPool) {
    return@async value + 1
}
private fun uiMethod1() {
    // Main thread
    launch(UI) {
        // Background thread
        asyncPlus1(1).await().let {
            // Main thread
            text_view.text = it.toString()
        }
    }
}

Kotlin 1.3

private fun asyncPlus1(value: Int): Int {
    return value + 1
}
private fun uiMethod1() {
    // Main thread
    GlobalScope.launch(Dispatchers.Main) {
        // Background thread
        async { asyncPlus1(1) }.await().let {
            // Main thread
            text_view.text = it.toString()
        }
    }
}

書き方はもっといろいろな書き方があるようです。
Coroutine 公式ドキュメントはこちらです。
https://kotlinlang.org/docs/reference/coroutines-overview.html

以下は、Kotlin 1.2時代に参考にさせていただいていた記事です。

Kotlin+Androidでasync/await
https://qiita.com/k-kagurazaka@github/items/702c92bc3381af36db12

入門Kotlin coroutines
https://qiita.com/k-kagurazaka@github/items/8595ca60a5c8d31bbe37

5
13
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
13