Skip to content
Update Kotlin coroutines authored by umaumax's avatar umaumax
......@@ -98,12 +98,14 @@ async function's result is 42
`.await()`を実行すると、その結果が返却されるまでこのコードの次の処理はブロックされる
## Dispatchers
### Dispatchers.Default
[Dispatchers.Default]( https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-default.html )
スレッドの最大数はCPUコアの数と同じ(ただし、2並列以上)
デフォルトで提供されるディスパッチャーでコルーチンを実行させたい場合は`async(Dispatchers.Default)``withContext(Dispatchers.Default)``launch(Dispatchers.Default)`などとする
### Dispatchers.Main
[Dispatchers.Main]( https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-main.html )
これはmain関数を実行しているスレッドではなく、UIを制御しているスレッドを指す
......@@ -127,6 +129,7 @@ launch(Dispatchers.Default): DefaultDispatcher-worker-1
launch(): main
```
### Dispatchers.Unconfined
[Coroutine context and dispatchers | Kotlin Documentation]( https://kotlinlang.org/docs/coroutine-context-and-dispatchers.html#unconfined-vs-confined-dispatcher )
`Dispatchers.Unconfined`は最初のsuspend地点まで現在のコンテキストで、それ以降のコンテキストは保証されない
......@@ -151,7 +154,14 @@ Unconfined : After delay in thread kotlinx.coroutines.DefaultExecutor
main runBlocking: After delay in thread main
```
## withContext
### Dispatchers.IO
I/O バウンドなタスクを実行するときに利用する
## コンテキスト
### launch
`launch(context = Dispatchers.IO) { }`とすることでコンテキストを指定できる
### withContext
[Kotlin coroutine withContext とは - Qiita]( https://qiita.com/favolabo/items/1e8ae7f32bc0917189fb )
`withContext(dispatcher)`を利用すると、コルーチンのコンテキストを切り替えることができる
......
......