Skip to content

Instantly share code, notes, and snippets.

@salamanders
Created September 30, 2019 21:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 = this@toFlow.addSnapshotListener { snapshots, e ->
if (e != null) {
logger.error { "${this@toFlow.path} listen:error:$e" }
cancel(CancellationException("Collection Listener Error in ${this@toFlow.path}", 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