异步编程:Firestore与Combine调度器的应用
1. Firestore数据获取与Combine适配
Firestore具备实时同步功能,但有时按需获取数据更为合适。在Combine中实现按需获取数据,可借助 Future 创建单次发布器。
以下是订阅和取消订阅的代码示例:
func subscribe() {
cancellable = db.collection("books").snapshotPublisher()
.tryMap { querySnapshot in
try querySnapshot.documents.compactMap {
documentSnapshot in
try documentSnapshot.data(as: Book.self)
}
}
.replaceError(with: [Book]())
.handleEvents(receiveCancel: {
print("Cancelled")
})
.assign(to: \.books, on: self)
}
func unsubscribe() {
cancellable?.cancel()
}
为了从Firestore获取单个文档,我们可以为 DocumentReference 创建扩展:
超级会员免费看
订阅专栏 解锁全文
78

被折叠的 条评论
为什么被折叠?



