Skip to content
GitLab
Menu
Why GitLab
Pricing
Contact Sales
Explore
Why GitLab
Pricing
Contact Sales
Explore
Sign in
Get free trial
Changes
Page history
Update Kotlin coroutines
authored
Jul 30, 2023
by
umaumax
Show whitespace changes
Inline
Side-by-side
Kotlin-coroutines.md
View page @
d0bc3b7c
...
...
@@ -107,6 +107,25 @@ Unconfined : After delay in thread kotlinx.coroutines.DefaultExecutor
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である
...
...
@@ -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
*
`launch`
は
`runBlocking`
や
`coroutineScope`
などのスコープ内でしか利用できない
...
...
...
...