kotlin/dispatcher
Kotlin には次のような組み込みディスパッチャが用意されている
コルーチンはメインの Android スレッドで実行されます。
主に、UI の更新や操作を処理し、迅速に処理を行うために使用します。
メインスレッドの外部でディスクまたはネットワークの I/O を行う場合に適しています。
たとえば、ファイルの読み書き、ネットワーク オペレーションの実行など
メインスレッドの外部でコンピューティング負荷の高い処理を行う。
たとえば、ビットマップ画像ファイルの処理など
メインスレッドをブロックしないようにして、新しいイベントがトリガーされたらすぐに処理を実行できるようにすることが目標
ディスパッチャを切り替え、各タイミングで現在のスレッドを表示する例
code:kotlin
import kotlinx.coroutines.*
fun main() {
runBlocking {
println("${Thread.currentThread().name} - runBlocking function")
launch {
println("${Thread.currentThread().name} - launch function")
withContext(Dispatchers.Default) {
println("${Thread.currentThread().name} - withContext function")
delay(1000)
println("10 results found.")
}
println("${Thread.currentThread().name} - end of launch function")
}
println("Loading...")
}
}
code:出力
main @coroutine#1 - runBlocking function
Loading...
main @coroutine#2 - launch function
DefaultDispatcher-worker-1 @coroutine#2 - withContext function
10 results found.
main @coroutine#2 - end of launch function