Skip to content

Instantly share code, notes, and snippets.

@salamanders
Created September 30, 2019 21:56
Show Gist options
  • Save salamanders/320ab3ed939da162b12b71d54877c0d8 to your computer and use it in GitHub Desktop.
Save salamanders/320ab3ed939da162b12b71d54877c0d8 to your computer and use it in GitHub Desktop.
Kotlin Firestore API (Collection documentChanges) to Flow
@ExperimentalCoroutinesApi
fun CollectionReference.toFlow(): Flow<DocumentChange> = callbackFlow {
val snapshotListener = [email protected] { snapshots, e ->
if (e != null) {
logger.error { "${[email protected]} listen:error:$e" }
cancel(CancellationException("Collection Listener Error in ${[email protected]}", e))
return@addSnapshotListener
}
for (dc in snapshots!!.documentChanges) {
offer(dc)
}
}
awaitClose {
logger.info { "Closing collection's flow, removing listener." }
snapshotListener.remove()
}
}
fun main() {
val myDispatcher = Executors.newFixedThreadPool(4).asCoroutineDispatcher()
runBlocking(myDispatcher) {
commandsRef.toFlow()
.filter { dc -> dc.type == DocumentChange.Type.ADDED }
.collect { dc ->
println(dc.document["somepropkey"] as String)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment