Cloud Firestore provides real-time database synchronization with Jetpack Compose.
Firestore Repository with CallbackFlow
class TaskRepository(private val firestore: FirebaseFirestore) {
fun getTasks(): Flow<List<Task>> = callbackFlow {
val listener = firestore.collection("tasks")
.addSnapshotListener { snapshot, error ->
if (error != null) {
close(error)
return@addSnapshotListener
}
val tasks = snapshot?.documents?.map { doc ->
doc.toObject(Task::class.java)!!
} ?: emptyList()
trySend(tasks)
}
awaitClose { listener.remove() }
}
}
Real-Time Sync with addSnapshotListener
fun addTask(task: Task) {
firestore.collection("tasks")
.add(task)
.addOnSuccessListener { ref -> task.id = ref.id }
.addOnFailureListener { e -> Log.e("Firestore", e) }
}
fun updateTask(taskId: String, updates: Map<String, Any>) {
firestore.collection("tasks").document(taskId).update(updates)
}
fun deleteTask(taskId: String) {
firestore.collection("tasks").document(taskId).delete()
}
ViewModel Integration
class TaskViewModel(private val repo: TaskRepository) : ViewModel() {
val tasks: StateFlow<List<Task>> = repo.getTasks()
.stateIn(viewModelScope, SharingStarted.Lazily, emptyList())
fun addTask(title: String) {
viewModelScope.launch {
repo.addTask(Task(title = title))
}
}
}
TaskList Screen
@Composable
fun TaskListScreen(viewModel: TaskViewModel) {
val tasks by viewModel.tasks.collectAsState()
LazyColumn {
items(tasks) { task ->
TaskItem(task) { viewModel.deleteTask(task.id) }
}
}
}
Firestore automatically syncs across devices—changes appear instantly in Compose UI via StateFlow.
8 production-ready Android app templates on Gumroad.
Browse templates → Gumroad
Top comments (0)