Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Created November 14, 2019 13:36
Show Gist options
  • Save manuelvicnt/55d0327af8d83c9912c007ba20949656 to your computer and use it in GitHub Desktop.
Save manuelvicnt/55d0327af8d83c9912c007ba20949656 to your computer and use it in GitHub Desktop.
/* Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
override fun getObservableUserEvent(userId: String, eventId: SessionId): Flow<UserEventResult> {
// 1) Create Flow with channelFlow
return channelFlow<UserEventResult> {
val eventDocument = firestore.collection(USERS_COLLECTION)
.document(userId)
.collection(EVENTS_COLLECTION)
.document(eventId)
// 1) Register callback to the API
val subscription = eventDocument.addSnapshotListener { snapshot, _ ->
val userEvent = if (snapshot.exists()) {
parseUserEvent(snapshot)
} else { null }
// 2) Send items to the Flow
channel.offer(UserEventResult(userEvent))
}
// 3) Don't close the stream of data, keep it open until the consumer
// stops listening or the API calls onCompleted or onError.
// When that happens, cancel the subscription to the 3P library
awaitClose { subscription.remove() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment