Skip to content
Update Kotlin coroutines authored by umaumax's avatar umaumax
...@@ -107,6 +107,25 @@ Unconfined : After delay in thread kotlinx.coroutines.DefaultExecutor ...@@ -107,6 +107,25 @@ Unconfined : After delay in thread kotlinx.coroutines.DefaultExecutor
main runBlocking: After delay in thread main main runBlocking: After delay in thread main
``` ```
## withContext
[Kotlin coroutine withContext とは - Qiita]( https://qiita.com/favolabo/items/1e8ae7f32bc0917189fb )
`withContext(dispatcher)`を利用すると、コルーチンのコンテキストを切り替えることができる
`async`は新たなcouroutineが生成されるが、`withContext`はコンテキストの切り替えのみとなる(下記は新しいコルーチンを利用するか、既存のコルーチンを使い回すのかの違いのみ)
``` kotlin
val result = async(Dispatchers.Default) {
"hoge"
}.await()
println(result)
```
``` kotlin
val result = withContext(Dispatchers.Default) {
"hoge"
}
println(result)
```
## コルーチンの並列度 ## コルーチンの並列度
rustのtokioと同じように明示的に別のスレッドを利用しない限り、コルーチンの同時実行数は1である rustのtokioと同じように明示的に別のスレッドを利用しない限り、コルーチンの同時実行数は1である
...@@ -204,6 +223,13 @@ end 3 ...@@ -204,6 +223,13 @@ end 3
``` ```
となる となる
## デバッグ
jvmに`-Dkotlinx.coroutines.debug`オプションを付与する
e.g. `java -Dkotlinx.coroutines.debug -jar ./app/build/libs/app-jvm.jar`
`Thread.currentThread().name`の出力が、`main`から`main @coroutine#1`のようになる
## トラブルシューティング ## トラブルシューティング
### Unresolved reference: launch ### Unresolved reference: launch
* `launch``runBlocking``coroutineScope`などのスコープ内でしか利用できない * `launch``runBlocking``coroutineScope`などのスコープ内でしか利用できない
... ...
......