Created
September 30, 2019 21:56
-
-
Save salamanders/320ab3ed939da162b12b71d54877c0d8 to your computer and use it in GitHub Desktop.
Kotlin Firestore API (Collection documentChanges) to Flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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