メインコンテンツにスキップ

🎛️ 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)
}

Dispatchers.Default

suspend fun heavyComputation(): Int = withContext(Dispatchers.Default) {
// CPU集約的な計算
var result = 0
repeat(1_000_000) {
result += it
}
result
}

fun main() = runBlocking {
val result = heavyComputation()
println("計算結果: $result")
}

🎯 実戦例

レイヤー別Dispatcher

// Repository - IO
class UserRepository {
suspend fun fetchUser(id: String): User = withContext(Dispatchers.IO) {
delay(1000) // ネットワークリクエスト
User(id, "田中太郎")
}
}

// UseCase - Default
class ProcessUserUseCase {
suspend fun process(user: User): ProcessedUser = withContext(Dispatchers.Default) {
// データ処理
delay(500)
ProcessedUser(user.name.uppercase())
}
}

data class User(val id: String, val name: String)
data class ProcessedUser(val displayName: String)

fun main() = runBlocking {
val repo = UserRepository()
val useCase = ProcessUserUseCase()

val user = repo.fetchUser("123")
val processed = useCase.process(user)
println("結果: ${processed.displayName}")
}

並列IO作業

suspend fun loadAllData(): Triple<String, String, String> = coroutineScope {
val user = async(Dispatchers.IO) {
delay(1000)
"ユーザーデータ"
}

val posts = async(Dispatchers.IO) {
delay(1500)
"投稿データ"
}

val comments = async(Dispatchers.IO) {
delay(800)
"コメントデータ"
}

Triple(user.await(), posts.await(), comments.await())
}

fun main() = runBlocking {
val time = measureTimeMillis {
val (user, posts, comments) = loadAllData()
println("$user, $posts, $comments")
}
println("所要時間: ${time}ms") // ~1500ms (並列)
}

🔧 Contextの組み合わせ

名前を付ける

fun main() = runBlocking {
launch(CoroutineName("作業1")) {
println("名前: ${coroutineContext[CoroutineName]}")
}

launch(Dispatchers.IO + CoroutineName("IO作業")) {
println("スレッド: ${Thread.currentThread().name}")
println("名前: ${coroutineContext[CoroutineName]}")
}

delay(100)
}

Jobの追加

fun main() = runBlocking {
val job = Job()

launch(job + Dispatchers.Default) {
println("作業実行")
delay(1000)
println("作業完了")
}

delay(500)
println("作業キャンセル")
job.cancel()
}

🎨 withContext

スレッド切り替え

suspend fun complexTask() {
println("開始: ${Thread.currentThread().name}")

// IO作業
val data = withContext(Dispatchers.IO) {
println("IO: ${Thread.currentThread().name}")
"データ"
}

// CPU作業
val processed = withContext(Dispatchers.Default) {
println("Default: ${Thread.currentThread().name}")
data.uppercase()
}

println("終了: ${Thread.currentThread().name}")
println("結果: $processed")
}

fun main() = runBlocking {
complexTask()
}

最適化パターン

// ❌ 不要な切り替え
suspend fun bad() {
withContext(Dispatchers.IO) {
val data1 = loadData1()
withContext(Dispatchers.Default) { // 不要!
process(data1)
}
}
}

// ✅ 効率的
suspend fun good() {
val data1 = withContext(Dispatchers.IO) {
loadData1()
}

withContext(Dispatchers.Default) {
process(data1)
}
}

suspend fun loadData1() = delay(100)
suspend fun process(data: Unit) = delay(100)

🔥 実用パターン

キャッシュ + ネットワーク

class DataSource {
private var cache: String? = null

suspend fun getData(): String {
// キャッシュ確認 (速い)
cache?.let { return it }

// ネットワークリクエスト (遅い)
return withContext(Dispatchers.IO) {
delay(1000)
"新しいデータ"
}.also { cache = it }
}
}

fun main() = runBlocking {
val source = DataSource()

// 最初の呼び出し - ネットワーク
val time1 = measureTimeMillis {
println(source.getData())
}
println("最初の呼び出し: ${time1}ms")

// 2回目 - キャッシュ
val time2 = measureTimeMillis {
println(source.getData())
}
println("2回目: ${time2}ms")
}

バッチ処理

suspend fun processBatch(items: List<Int>): List<Int> {
return withContext(Dispatchers.Default) {
items.map { item ->
// 各アイテムを処理
item * 2
}
}
}

fun main() = runBlocking {
val items = List(100) { it }
val results = processBatch(items)
println("処理完了: ${results.size}個")
}

タイムアウトと一緒に

suspend fun fetchWithTimeout(): String? {
return try {
withTimeout(2000) {
withContext(Dispatchers.IO) {
delay(3000) // 時間がかかりすぎる
"データ"
}
}
} catch (e: TimeoutCancellationException) {
null
}
}

fun main() = runBlocking {
val result = fetchWithTimeout()
println("結果: ${result ?: "タイムアウト"}")
}

🛡️ 例外処理

CoroutineExceptionHandler

fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, exception ->
println("エラー処理: ${exception.message}")
}

val job = launch(handler) {
throw Exception("問題が発生しました!")
}

job.join()
println("実行を続けます")
}

SupervisorJob

fun main() = runBlocking {
val supervisor = SupervisorJob()

with(CoroutineScope(coroutineContext + supervisor)) {
val job1 = launch {
delay(500)
throw Exception("作業1失敗")
}

val job2 = launch {
delay(1000)
println("作業2成功!")
}

try {
job1.join()
} catch (e: Exception) {
println("作業1例外: ${e.message}")
}

job2.join()
}
}

🎯 カスタムDispatcher

スレッドプールのサイズ指定

fun main() = runBlocking {
val customDispatcher = Dispatchers.IO.limitedParallelism(2)

repeat(5) { i ->
launch(customDispatcher) {
println("作業 $i: ${Thread.currentThread().name}")
delay(1000)
}
}

delay(3000)
}

単一スレッド

fun main() = runBlocking {
val singleThread = Dispatchers.Default.limitedParallelism(1)

repeat(3) { i ->
launch(singleThread) {
println("作業 $i: ${Thread.currentThread().name}")
delay(500)
}
}

delay(2000)
}

🤔 よくある質問

Q1. どのDispatcherを使えばいいですか?

A: 作業の種類に応じて選択してください!

// IO - ネットワーク、ファイル、データベース
suspend fun fetchData() = withContext(Dispatchers.IO) { }

// Default - CPU集約的な計算
suspend fun compute() = withContext(Dispatchers.Default) { }

// Main - UI更新 (Android/Desktop)
suspend fun updateUI() = withContext(Dispatchers.Main) { }

Q2. withContextを何度も使ってもいいですか?

A: はい! 必要なときに切り替えてください。

suspend fun workflow() {
val data = withContext(Dispatchers.IO) {
loadFromNetwork()
}

val processed = withContext(Dispatchers.Default) {
processData(data)
}

withContext(Dispatchers.Main) {
updateUI(processed)
}
}

Q3. Dispatcherを指定しない場合は?

A: 親コルーチンのContextを継承します!

fun main() = runBlocking(Dispatchers.Default) {
launch { // Dispatchers.Defaultを継承
println(Thread.currentThread().name)
}
}

🎬 まとめ

ContextとDispatcherでコルーチンを制御しましょう!

重要ポイント:
✅ Dispatchers.IO - ネットワーク/ファイル
✅ Dispatchers.Default - CPU作業
✅ Dispatchers.Main - UI更新
✅ withContextでスレッド切り替え
✅ Contextの組み合わせで細かい制御

おめでとうございます! Coroutinesシリーズを完了しました! 🎉

次のステップ: 単体テストでテストの書き方を学びましょう!