0Pricing
Jetpack Compose Academy · Lección

Consultas reactivas que devuelven Flow

Observe la base de datos en Compose.

Consultas reactivas que devuelven Flow es una lección gratuita de Jetpack Compose Academy en CoddyKit. Esta es la lección 2 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.

Static Reads Go Stale

A one-time query gives you data once, but the table keeps changing. You want the UI to refresh whenever rows are added or removed.

Return a Flow Instead

Change a DAO query to return a Flow. Room now emits a fresh list every single time the underlying table changes. 🔄

@Query("SELECT * FROM Note")
fun observeAll(): Flow<List<Note>>

No suspend on Flow Queries

A Flow query is not marked suspend. It returns the stream immediately, and emissions arrive as the data updates over time.

Room Watches the Tables

Behind the scenes Room tracks which tables a query touches. When any of them changes, it re-runs the query and emits a new value.

Collect the Flow Safely

In your ViewModel, collect the Flow inside a coroutine. Use viewModelScope so collection stops when the ViewModel clears.

viewModelScope.launch {
    dao.observeAll().collect { notes -> /* update state */ }
}

Turn Flow Into State

Convert the stream into observable UI state with stateIn, giving an initial value so the screen has something to show at once.

val notes = dao.observeAll().stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())

Observe It in Compose

In the Composable read the StateFlow with collectAsStateWithLifecycle. The list recomposes automatically on every change.

val notes by viewModel.notes.collectAsStateWithLifecycle()

Insert and Watch It Appear

Insert a row anywhere and the Flow emits again, so the new item shows up instantly without you refreshing manually.

Map Inside the Flow

You can transform results with map before they reach the UI, like sorting or filtering, all reactively in the stream.

dao.observeAll().map { it.sortedBy(Note::text) }

Flows Beat LiveData Here

Flow integrates cleanly with coroutines and Compose, making it the modern choice over LiveData for reactive Room queries.

One Source, Always Current

With reactive queries the database becomes your single source of truth, and the UI is just a reflection of it at every moment.

Quick Check

What happens when a Room DAO query returns a Flow?

Recap: Reactive Reads

You made queries return Flow, collected them into state, and watched Compose redraw on every change. Next you will organize this behind a repository.

Preguntas frecuentes

¿La lección «Consultas reactivas que devuelven Flow» es gratis?

Sí — el texto completo de «Consultas reactivas que devuelven Flow» 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 «Consultas reactivas que devuelven Flow»?

Observe la base de datos en Compose. 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 2 de 4.

¿Cuánto tiempo toma la lección «Consultas reactivas que devuelven Flow»?

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

  1. Entidades, DAOs y la base de datos
  2. Consultas reactivas que devuelven Flow
  3. El patrón Repository
  4. Estrategia de almacenamiento offline-first
← Volver a Jetpack Compose Academy