Last active
June 16, 2022 08:49
-
-
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
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 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