-
-
Save byaruhaf/3ce87ddb1846b777553168ec299eade6 to your computer and use it in GitHub Desktop.
Wrap Firestore's addSnapshotListner method for use with AsyncThrowingStream.
This file contains hidden or 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