Skip to content

Instantly share code, notes, and snippets.

@yimajo
Created March 17, 2023 15:22
Show Gist options
  • Save yimajo/ca4e7936739a6275f1eb48e515370e3e to your computer and use it in GitHub Desktop.
Save yimajo/ca4e7936739a6275f1eb48e515370e3e to your computer and use it in GitHub Desktop.
Wrap Firestore's addSnapshotListner method for use with AsyncThrowingStream.
import FirebaseFirestore
// MARK: - async
extension Query {
func addSnapshotListener<T>(
includeMetadataChanges: Bool = false
) -> AsyncThrowingStream<[T], Error> where T: Decodable{
.init { continuation in
let listener = addSnapshotListener(includeMetadataChanges: includeMetadataChanges) { result in
do {
let snapshot = try result.get()
continuation.yield(try snapshot.documents.map { try $0.data(as: T.self) })
} catch {
continuation.finish(throwing: error)
}
}
continuation.onTermination = { @Sendable _ in
listener.remove()
}
}
}
}
// MARK: - Result
extension Query {
func addSnapshotListener(
includeMetadataChanges: Bool = false,
listener: @escaping (Result<QuerySnapshot, Error>) -> ()
) -> some ListenerRegistration {
addSnapshotListener(includeMetadataChanges: includeMetadataChanges) { snapshot, error in
if let error {
listener(.failure(error))
} else {
listener(.success(snapshot!))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment