Passer au contenu principal

🌊 Flow

📖 Qu'est-ce que Flow ?

Flow est un flux de données qui retourne plusieurs valeurs de manière séquentielle et asynchrone. Vous pouvez le considérer comme une version liste d'une fonction suspend !

💡 Concepts de base

Valeur unique vs valeurs multiples

// suspend - une seule valeur
suspend fun fetchData(): String {
delay(1000)
return "데이터"
}

// Flow - plusieurs valeurs
fun fetchDataStream(): Flow<String> = flow {
emit("데이터1")
delay(500)
emit("데이터2")
delay(500)
emit("데이터3")
}

fun main() = runBlocking {
// Valeur unique
println(fetchData())

// Plusieurs valeurs
fetchDataStream().collect { value ->
println(value)
}
}

Création de Flow

import kotlinx.coroutines.flow.*

fun main() = runBlocking {
// 1. Constructeur 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) }
}

🎯 Exemples pratiques

Données en temps réel

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

fun main() = runBlocking {
tickerFlow().collect { value ->
println("$value 초 경과")
}
}

Détection de changements dans la base de données

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}") }
}
}

Données de capteur

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")
}
}

🔧 Opérateurs Flow

map - Transformation

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

filter - Filtrage

fun main() = runBlocking {
flowOf(1, 2, 3, 4, 5)
.filter { it % 2 == 0 } // Nombres pairs uniquement
.collect { println(it) }
// 2, 4
}

transform - Transformation complexe

fun main() = runBlocking {
flowOf(1, 2, 3)
.transform { value ->
emit("변환: $value")
emit("제곱: ${value * value}")
}
.collect { println(it) }
}

take - Limitation du nombre

fun main() = runBlocking {
flowOf(1, 2, 3, 4, 5)
.take(3) // Seulement les 3 premiers
.collect { println(it) }
// 1, 2, 3
}

🎨 Opérateurs avancés

buffer - Mise en tampon

fun main() = runBlocking {
val time = measureTimeMillis {
flow {
repeat(3) {
delay(100)
emit(it)
}
}
.buffer() // Amélioration des performances avec la mise en tampon
.collect {
delay(300)
println(it)
}
}
println("소요 시간: ${time}ms")
}

conflate - Dernière valeur uniquement

fun main() = runBlocking {
flow {
repeat(5) {
delay(100)
emit(it)
}
}
.conflate() // Sauter les valeurs intermédiaires si le collecteur est lent
.collect {
delay(300)
println("수집: $it")
}
}

zip - Combinaison

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 - Association

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

🔥 Patterns pratiques

Fonction de recherche

fun searchQuery(query: String): Flow<List<String>> = flow {
delay(300) // Debounce
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")
}
}

Pagination

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")
}
}

Gestion des erreurs

fun riskyFlow(): Flow<Int> = flow {
emit(1)
emit(2)
throw Exception("에러 발생!")
emit(3)
}

fun main() = runBlocking {
riskyFlow()
.catch { e ->
println("에러 잡음: ${e.message}")
emit(-1) // Valeur par défaut
}
.collect { println("값: $it") }
}

Réessai

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 et SharedFlow

StateFlow - Gestion d'état

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 - Événements

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()

// Abonné 1
launch {
bus.events.collect { event ->
println("구독자1: $event")
}
}

// Abonné 2
launch {
bus.events.collect { event ->
println("구독자2: $event")
}
}

delay(100)
bus.emit("이벤트1")
delay(100)
bus.emit("이벤트2")
delay(100)
}

🤔 Questions fréquentes

Q1. Quand Flow s'exécute-t-il ?

R: Il s'exécute lorsque vous appelez 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. Quelle est la différence entre List et Flow ?

R: List est immédiat, Flow est progressif !

fun main() = runBlocking {
// List - toutes les données en mémoire
val list = listOf(1, 2, 3)

// Flow - généré au besoin
val flow = flow {
repeat(3) {
delay(1000)
emit(it)
}
}
}

Q3. Que se passe-t-il si vous collectez Flow plusieurs fois ?

R: Il s'exécute à nouveau à chaque fois !

fun main() = runBlocking {
val flow = flow {
println("실행!")
emit(1)
}

flow.collect { println("첫 수집: $it") }
flow.collect { println("두 수집: $it") }
}
// 실행!
// 첫 수집: 1
// 실행!
// 두 수집: 1

🎬 En conclusion

Programmation réactive avec Flow !

Résumé des points clés :
✅ Flux de données asynchrones
✅ Cold Stream (exécution lors de la collecte)
✅ Opérateurs comme map, filter, etc.
✅ Gestion d'état avec StateFlow
✅ Transmission d'événements avec SharedFlow

Prochaine étape : Découvrez l'environnement d'exécution des coroutines dans Context et Dispatcher !