🎛️ Context & Dispatcher
📖 什麼是 CoroutineContext?
CoroutineContext 是決定協程如何執行的設定集合。它指定在哪個執行緒上執行、名稱是什麼等等!
💡 Dispatcher
基本 Dispatcher
fun main() = runBlocking {
// Main - UI 執行緒 (Android/Desktop)
launch(Dispatchers.Main) {
// UI 更新
}
// IO - 網路/檔案操作
launch(Dispatchers.IO) {
println("IO: ${Thread.currentThread().name}")
}
// Default - CPU 密集型操作
launch(Dispatchers.Default) {
println("Default: ${Thread.currentThread().name}")
}
// Unconfined - 特殊情況
launch(Dispatchers.Unconfined) {
println("Unconfined: ${Thread.currentThread().name}")
}
delay(100)
}
Dispatchers.IO
suspend fun readFile(): String = withContext(Dispatchers.IO) {
// 讀取檔案、網路請求等
delay(1000)
"檔案內容"
}
suspend fun writeFile(content: String) = withContext(Dispatchers.IO) {
// 寫入檔案
delay(500)
println("儲存檔案: $content")
}
fun main() = runBlocking {
val content = readFile()
writeFile(content)
}