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

🌊 Flow

📖 Flowとは?

Flowは非同期的に複数の値を順次返すデータストリームです。suspend関数のリスト版のようなものだと考えると分かりやすいです!

💡 基本概念

単一値 vs 複数値

// suspend - 1つの値
suspend fun fetchData(): String {
delay(1000)
return "データ"
}

// Flow - 複数の値
fun fetchDataStream(): Flow<String> = flow {
emit("データ1")
delay(500)
emit("データ2")
delay(500)
emit("データ3")
}

fun main() = runBlocking {
// 単一値
println(fetchData())

// 複数値
fetchDataStream().collect { value ->
println(value)
}
}

Flowの生成

import kotlinx.coroutines.flow.*

fun main() = runBlocking {
// 1. flowビルダー
val flow1 = flow {
emit(1)
emit(2)
emit(3)
}

// 2. flowOf
val flow2 = flowOf(1, 2, 3)

// 3. asFlow
val flow3 = listOf(1, 2, 3).asFlow()

flow1.collect { println(it) }
}

🎯 実践例

リアルタイムデータ

fun tickerFlow(): Flow<Int> = flow {
var counter = 0
while (counter < 5) {
emit(counter++)
delay(1000)
}
}

fun main() = runBlocking {
tickerFlow().collect { value ->
println("$value 秒経過")
}
}

データベース変更の監視

data class User(val id: Int, val name: String)

fun observeUsers(): Flow<List<User>> = flow {
repeat(3) { i ->
delay(1000)
val users = listOf(
User(i * 2, "ユーザー${i * 2}"),
User(i * 2 + 1, "ユーザー${i * 2 + 1}")
)
emit(users)
}
}

fun main() = runBlocking {
observeUsers().collect { users ->
println("更新されたユーザー:")
users.forEach { println(" - ${it.name}") }
}
}

センサーデータ

fun sensorData(): Flow<Double> = flow {
repeat(10) {
val reading = (20..30).random() + Math.random()
emit(reading)
delay(500)
}
}

fun main() = runBlocking {
sensorData().collect { temperature ->
println("温度: ${"%.1f".format(temperature)}°C")
}
}

🔧 Flow演算子

map - 変換

fun main() = runBlocking {
flowOf(1, 2, 3, 4, 5)
.map { it * it } // 二乗
.collect { println(it) }
// 1, 4, 9, 16, 25
}

filter - フィルタリング

fun main() = runBlocking {
flowOf(1, 2, 3, 4, 5)
.filter { it % 2 == 0 } // 偶数のみ
.collect { println(it) }
// 2, 4
}

transform - 複雑な変換

fun main() = runBlocking {
flowOf(1, 2, 3)
.transform { value ->
emit("変換: $value")
emit("二乗: ${value * value}")
}
.collect { println(it) }
}

take - 個数制限

fun main() = runBlocking {
flowOf(1, 2, 3, 4, 5)
.take(3) // 最初の3つのみ
.collect { println(it) }
// 1, 2, 3
}

🎨 高度な演算子

buffer - バッファリング

fun main() = runBlocking {
val time = measureTimeMillis {
flow {
repeat(3) {
delay(100)
emit(it)
}
}
.buffer() // バッファリングでパフォーマンス向上
.collect {
delay(300)
println(it)
}
}
println("所要時間: ${time}ms")
}

conflate - 最新値のみ

fun main() = runBlocking {
flow {
repeat(5) {
delay(100)
emit(it)
}
}
.conflate() // 遅いコレクターがいる場合、中間値をスキップ
.collect {
delay(300)
println("収集: $it")
}
}

zip - 結合

fun main() = runBlocking {
val numbers = flowOf(1, 2, 3)
val strings = flowOf("一", "二", "三")

numbers.zip(strings) { num, str ->
"$num - $str"
}.collect { println(it) }
// 1 - 一
// 2 - 二
// 3 - 三
}

combine - 組み合わせ

fun main() = runBlocking {
val flow1 = flow {
emit("A")
delay(500)
emit("B")
}

val flow2 = flow {
emit(1)
delay(200)
emit(2)
delay(200)
emit(3)
}

flow1.combine(flow2) { a, b ->
"$a$b"
}.collect { println(it) }
}

🔥 実用的なパターン

検索機能

fun searchQuery(query: String): Flow<List<String>> = flow {
delay(300) // デバウンス
val results = listOf(
"${query}1",
"${query}2",
"${query}3"
).filter { it.contains(query) }
emit(results)
}

fun main() = runBlocking {
flowOf("kot", "kotlin", "kotli")
.flatMapLatest { query ->
searchQuery(query)
}
.collect { results ->
println("検索結果: $results")
}
}

ページネーション

fun loadPage(page: Int): Flow<List<String>> = flow {
delay(500)
val items = List(10) { "アイテム${page * 10 + it}" }
emit(items)
}

fun main() = runBlocking {
flowOf(1, 2, 3)
.flatMapConcat { page ->
loadPage(page)
}
.collect { items ->
println("ページ読み込み: $items")
}
}

エラー処理

fun riskyFlow(): Flow<Int> = flow {
emit(1)
emit(2)
throw Exception("エラー発生!")
emit(3)
}

fun main() = runBlocking {
riskyFlow()
.catch { e ->
println("エラーをキャッチ: ${e.message}")
emit(-1) // デフォルト値
}
.collect { println("値: $it") }
}

リトライ

var attemptCount = 0

fun unstableFlow(): Flow<String> = flow {
attemptCount++
if (attemptCount < 3) {
throw Exception("一時的なエラー")
}
emit("成功!")
}

fun main() = runBlocking {
unstableFlow()
.retry(3) { cause ->
println("リトライ中... (${cause.message})")
delay(1000)
true
}
.collect { println(it) }
}

🛠️ StateFlowとSharedFlow

StateFlow - 状態管理

class Counter {
private val _count = MutableStateFlow(0)
val count: StateFlow<Int> = _count

fun increment() {
_count.value++
}
}

fun main() = runBlocking {
val counter = Counter()

launch {
counter.count.collect { value ->
println("カウント: $value")
}
}

delay(100)
counter.increment()
delay(100)
counter.increment()
delay(100)
}

SharedFlow - イベント

class EventBus {
private val _events = MutableSharedFlow<String>()
val events: SharedFlow<String> = _events

suspend fun emit(event: String) {
_events.emit(event)
}
}

fun main() = runBlocking {
val bus = EventBus()

// 購読者1
launch {
bus.events.collect { event ->
println("購読者1: $event")
}
}

// 購読者2
launch {
bus.events.collect { event ->
println("購読者2: $event")
}
}

delay(100)
bus.emit("イベント1")
delay(100)
bus.emit("イベント2")
delay(100)
}

🤔 よくある質問

Q1. Flowはいつ実行されますか?

A: collectを呼び出すときに実行されます(Cold Stream)!

fun main() = runBlocking {
val flow = flow {
println("Flow開始!")
emit(1)
}

println("Flow生成")
delay(1000)

println("collect呼び出し")
flow.collect { println(it) }
}
// Flow生成
// (1秒待機)
// collect呼び出し
// Flow開始!
// 1

Q2. ListとFlowの違いは?

A: Listは即座に、Flowは段階的に!

fun main() = runBlocking {
// List - すべてのデータがメモリに
val list = listOf(1, 2, 3)

// Flow - 必要なときに生成
val flow = flow {
repeat(3) {
delay(1000)
emit(it)
}
}
}

Q3. Flowを複数回収集すると?

A: 毎回新しく実行されます!

fun main() = runBlocking {
val flow = flow {
println("実行!")
emit(1)
}

flow.collect { println("1回目の収集: $it") }
flow.collect { println("2回目の収集: $it") }
}
// 実行!
// 1回目の収集: 1
// 実行!
// 2回目の収集: 1

🎬 おわりに

Flowでリアクティブプログラミングを!

要点まとめ:
✅ 非同期データストリーム
✅ Cold Stream(収集時に実行)
✅ map、filterなどの演算子
✅ StateFlowで状態管理
✅ SharedFlowでイベント伝達

次のステップ: ContextとDispatcherでコルーチンの実行環境について学びましょう!