Skip to content

Instantly share code, notes, and snippets.

@dabodamjan
Last active June 16, 2022 08:49
Show Gist options
  • Save dabodamjan/f8470686389bf7c84cc0bb4807e1f232 to your computer and use it in GitHub Desktop.
Save dabodamjan/f8470686389bf7c84cc0bb4807e1f232 to your computer and use it in GitHub Desktop.
Firebase Firestore snapshot publisher that maps snapshot documents to an array of your model data type
import Foundation
import Firebase
import FirebaseFirestore
import FirebaseFirestoreCombineSwift
import Combine
extension Query {
func snapshotArrayPublisher<T: Decodable>(
as type: T.Type,
includeMetadataChanges: Bool = false
) -> AnyPublisher<[T], Error> {
snapshotPublisher()
.tryMap { querySnapshot throws -> [T] in
let typeArray = try querySnapshot.documents.compactMap { queryDocumentSnapshot in
return try queryDocumentSnapshot.data(as: T.self)
}
return typeArray
}
.eraseToAnyPublisher()
}
}
// Usage in your code
var yourModelPublisher: AnyPublisher<[YourModel], Error> {
firestore.collection("yourCollectionName")
.snapshotArrayPublisher(as: YourModel.self)
.eraseToAnyPublisher()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment