Observe tabelas como Flow
Obtenha atualizações reativas quando o banco de dados mudar
Observe tabelas como Flow é uma aula grátis de Kotlin Multiplatform Academy no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Kotlin Multiplatform Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Kotlin Multiplatform Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Observe Instead of Poll
Re-running a query by hand misses changes. SQLDelight can push fresh results to you whenever the table changes.
Add the Coroutines Extension
Reactive queries need the coroutines-extensions artifact, which adds Flow support on top of your generated queries.
implementation("app.cash.sqldelight:coroutines-extensions:2.0.2")Turn a Query into a Flow
Call asFlow on any select query to get a Flow that re-emits whenever the underlying table is written.
val flow = queries.selectAll().asFlow()Map to Results
asFlow gives a query holder, so chain mapToList to emit a ready Kotlin list each time the data changes.
val players = queries.selectAll()
.asFlow()
.mapToList(Dispatchers.IO)Single-Row Streams
For one row use mapToOneOrNull, which emits the row or null and updates automatically as that row changes.
queries.selectById(1)
.asFlow()
.mapToOneOrNull(Dispatchers.IO)Collect in Shared Code
You consume the stream by collecting it. Every insert, update or delete to that table triggers a fresh emission.
players.collect { list -> render(list) }Expose It as StateFlow
Wrap the Flow in a StateFlow so your shared ViewModel holds the latest list as a single source of truth.
val state = players.stateIn(scope, SharingStarted.Eagerly, emptyList())Android Collects with Compose
On Android, collectAsState turns the StateFlow into Compose state, so the list recomposes automatically on every change.
val list by viewModel.state.collectAsState()iOS Collects from Swift
On iOS you observe the same StateFlow from Swift and update SwiftUI, so both apps stay in sync with the database.
One Write, Both UIs Update
Insert a row anywhere and every active Flow re-emits. The database becomes the live source driving both platforms.
Pick the Right Dispatcher
Run mapping off the main thread by passing a background dispatcher, keeping the UI smooth while queries run.
Quick Check
You collect selectAll().asFlow().mapToList(...). When does it emit again?
Recap: Live Data
You turned queries into Flows, mapped them to results, exposed StateFlow, and let both UIs update on every write. Your shared database is now reactive. ✅
Perguntas Frequentes
A aula “Observe tabelas como Flow” é grátis?
Sim — o texto completo de “Observe tabelas como Flow” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Kotlin Multiplatform Academy, atualize para CoddyKit PRO. O curso de Kotlin Multiplatform Academy inclui 4 aulas no total.
O que vou aprender em “Observe tabelas como Flow”?
Obtenha atualizações reativas quando o banco de dados mudar Você pratica Kotlin Multiplatform Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Kotlin Multiplatform Academy?
Nenhuma experiência prévia é necessária. Kotlin Multiplatform Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Observe tabelas como Flow”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Kotlin Multiplatform Academy?
Sim. Cada aula de Kotlin Multiplatform Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Adicione SQLDelight e escreva esquemas .sq
- Configuração do SqlDriver da plataforma
- Insira, consulte e atualize linhas
- Observe tabelas como Flow