LoginSignup
28
19

More than 3 years have passed since last update.

Kotlin coroutine withContext とは

Last updated at Posted at 2019-07-02

coroutineのコンテキストを切り替えるための中断関数。
以下の2つのコードの実行結果は変わらないが、async/awaitではcoroutineを新たに生成する一方、withContextは実行中のcoroutineのコンテキストを切り替えているだけです。なのでwithContextの方がパフォーマンスがよくメモリも食わない

GlobalScope.launch(Dispatchers.Main) {
    // メインスレッドでの何らかの処理1
    // ...

    // バックグラウンドスレッドで非同期処理をして待機して結果を取得
    val result = async(Dispatchers.Default) { // 新たなcouroutineが生成される
      blockInBackground()
    }.await()

    // メインスレッドでの何らかの処理2
    // ...
}
GlobalScope.launch(Dispatchers.Main) {
    // メインスレッドでの何らかの処理1
    // ...

    // バックグラウンドスレッドで非同期処理をして待機して結果を取得
    // couroutineのコンテキストが切り替わる(Main→Default)
    val result = withContext(Dispatchers.Default){
      blockInBackground()
    }
    // couroutineのコンテキストが切り替わる(Default→Main)

    // メインスレッドでの何らかの処理2
    // ...
}

間違っていたらご指摘いただけると幸いです。

参考)
https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html#coroutine-context-and-dispatchers

28
19
0

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
28
19