🌊 Flow
📖 ¿Qué es Flow?
Flow es un flujo de datos que devuelve múltiples valores de forma secuencial y asíncrona. ¡Puede pensarlo como una versión de lista de funciones suspend!
💡 Conceptos básicos
Valor único vs Múltiples valores
// suspend - un valor
suspend fun fetchData(): String {
delay(1000)
return "데이터"
}
// Flow - múltiples valores
fun fetchDataStream(): Flow<String> = flow {
emit("데이터1")
delay(500)
emit("데이터2")
delay(500)
emit("데이터3")
}
fun main() = runBlocking {
// Valor único
println(fetchData())
// Múltiples valores
fetchDataStream().collect { value ->
println(value)
}
}
Creación de Flow
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
// 1. Constructor 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) }
}
🎯 Ejemplos prácticos
Datos en tiempo real
fun tickerFlow(): Flow<Int> = flow {
var counter = 0
while (counter < 5) {
emit(counter++)
delay(1000)
}
}
fun main() = runBlocking {
tickerFlow().collect { value ->
println("$value 초 경과")
}
}
Detección de cambios en base de datos
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}") }
}
}
Datos de sensores
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")
}
}
🔧 Operadores de Flow
map - Transformación
fun main() = runBlocking {
flowOf(1, 2, 3, 4, 5)
.map { it * it } // Cuadrado
.collect { println(it) }
// 1, 4, 9, 16, 25
}
filter - Filtrado
fun main() = runBlocking {
flowOf(1, 2, 3, 4, 5)
.filter { it % 2 == 0 } // Solo pares
.collect { println(it) }
// 2, 4
}
transform - Transformación compleja
fun main() = runBlocking {
flowOf(1, 2, 3)
.transform { value ->
emit("변환: $value")
emit("제곱: ${value * value}")
}
.collect { println(it) }
}
take - Límite de cantidad
fun main() = runBlocking {
flowOf(1, 2, 3, 4, 5)
.take(3) // Solo los primeros 3
.collect { println(it) }
// 1, 2, 3
}
🎨 Operadores avanzados
buffer - Buffering
fun main() = runBlocking {
val time = measureTimeMillis {
flow {
repeat(3) {
delay(100)
emit(it)
}
}
.buffer() // Mejora de rendimiento con buffering
.collect {
delay(300)
println(it)
}
}
println("소요 시간: ${time}ms")
}
conflate - Solo el valor más reciente
fun main() = runBlocking {
flow {
repeat(5) {
delay(100)
emit(it)
}
}
.conflate() // Omite valores intermedios si el colector es lento
.collect {
delay(300)
println("수집: $it")
}
}
zip - Combinación
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 - Composición
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) }
}
🔥 Patrones prácticos
Funcionalidad de búsqueda
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")
}
}
Paginación
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")
}
}
Manejo de errores
fun riskyFlow(): Flow<Int> = flow {
emit(1)
emit(2)
throw Exception("에러 발생!")
emit(3)
}
fun main() = runBlocking {
riskyFlow()
.catch { e ->
println("에러 잡음: ${e.message}")
emit(-1) // Valor predeterminado
}
.collect { println("값: $it") }
}
Reintentos
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 y SharedFlow
StateFlow - Gestión de estado
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 - Eventos
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()
// Suscriptor 1
launch {
bus.events.collect { event ->
println("구독자1: $event")
}
}
// Suscriptor 2
launch {
bus.events.collect { event ->
println("구독자2: $event")
}
}
delay(100)
bus.emit("이벤트1")
delay(100)
bus.emit("이벤트2")
delay(100)
}
🤔 Preguntas frecuentes
Q1. ¿Cuándo se ejecuta Flow?
A: ¡Se ejecuta cuando se llama 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. ¿Cuál es la diferencia entre List y Flow?
A: ¡List es inmediato, Flow es progresivo!
fun main() = runBlocking {
// List - Todos los datos en memoria
val list = listOf(1, 2, 3)
// Flow - Generado cuando se necesita
val flow = flow {
repeat(3) {
delay(1000)
emit(it)
}
}
}
Q3. ¿Qué pasa si se recolecta Flow varias veces?
A: ¡Se ejecuta de nuevo cada vez!
fun main() = runBlocking {
val flow = flow {
println("실행!")
emit(1)
}
flow.collect { println("첫 수집: $it") }
flow.collect { println("두 수집: $it") }
}
// 실행!
// 첫 수집: 1
// 실행!
// 두 수집: 1
🎬 Conclusión
¡Programación reactiva con Flow!
Resumen clave:
✅ Flujo de datos asíncrono
✅ Cold Stream (se ejecuta al recolectar)
✅ Operadores como map, filter, etc.
✅ Gestión de estado con StateFlow
✅ Transmisión de eventos con SharedFlow
Siguiente paso: ¡Aprenda sobre el entorno de ejecución de corrutinas en Context y Dispatcher!