Created
March 17, 2023 15:22
-
-
Save yimajo/ca4e7936739a6275f1eb48e515370e3e to your computer and use it in GitHub Desktop.
Wrap Firestore's addSnapshotListner method for use with AsyncThrowingStream.
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
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