StateFlow frente a SharedFlow
Elija el hot stream adecuado para la interfaz.
StateFlow frente a SharedFlow es una lección gratuita de Jetpack Compose Academy en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Jetpack Compose Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Jetpack Compose Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Hot Streams for the UI
To stream live data into Compose you use a hot flow that stays active and emits whether or not anyone is currently collecting it.
Meet StateFlow
A StateFlow always holds exactly one current value. New collectors immediately receive that latest value, which is perfect for screen state. 📦
val count = MutableStateFlow(0)
count.value = 1Read the Value Anytime
Because StateFlow caches one item, you can read its current value synchronously through the value property without collecting.
val ui: StateFlow<UiState> = _ui
val now = ui.valueStateFlow Skips Duplicates
A StateFlow only emits when the value actually changes. Setting it to the same value again sends nothing to collectors.
_count.value = 5
_count.value = 5 // no new emissionMeet SharedFlow
A SharedFlow broadcasts events to many collectors but holds no required current value. It is built for things that happen, not state that is.
val events = MutableSharedFlow<String>()SharedFlow Replay Buffer
A SharedFlow can replay a few past emissions to late collectors. With replay zero, new collectors only see future events.
MutableSharedFlow<Int>(replay = 1)SharedFlow Keeps Duplicates
Unlike StateFlow, a SharedFlow emits every value you send, even repeats. Two identical taps fire two separate events.
events.emit("tap")
events.emit("tap") // both deliveredState Versus Events
The rule of thumb: use StateFlow for what the screen looks like, and SharedFlow for one-time things like a navigation or a toast.
Expose Read-Only Streams
Keep a private mutable flow inside the ViewModel and expose a read-only one. The UI observes but cannot mutate it.
private val _ui = MutableStateFlow(UiState())
val ui: StateFlow<UiState> = _uiStateFlow Needs a Default
A StateFlow must start with an initial value, so the UI always has something to show. A SharedFlow can start empty.
MutableStateFlow(UiState(loading = true))Collect in Compose
You turn either flow into Compose state with a collector. For a StateFlow the screen has data immediately on first frame.
val state by viewModel.ui.collectAsStateWithLifecycle()Quick Check
Match each flow to its purpose.
Recap: StateFlow vs SharedFlow
Nice! StateFlow caches one current value for screen state, while SharedFlow broadcasts repeatable events with an optional replay buffer. 🎯
Preguntas frecuentes
¿La lección «StateFlow frente a SharedFlow» es gratis?
Sí — el texto completo de «StateFlow frente a SharedFlow» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Jetpack Compose Academy, actualiza a CoddyKit PRO. El curso de Jetpack Compose Academy incluye 4 lecciones en total.
¿Qué aprenderé en «StateFlow frente a SharedFlow»?
Elija el hot stream adecuado para la interfaz. Practicas Jetpack Compose Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Jetpack Compose Academy?
No se requiere experiencia previa. Jetpack Compose Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «StateFlow frente a SharedFlow»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Jetpack Compose Academy?
Sí. Cada lección de Jetpack Compose Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- StateFlow frente a SharedFlow
- Mapear y combinar Flows
- stateIn y WhileSubscribed
- Eventos puntuales con Channels