0

我正在将一个 Firestore 数据库连接到我的 UI。

我创建了一个 SignedInAuthentication 对象,我将其设置为环境对象

class SignedInAuthentication: ObservableObject {
    @Published var user: User
    @Published var workoutCompletionStore: WorkoutCompletionDataStoreProtocol

    init(user: User, workoutCompletionStore: WorkoutCompletionDataStoreProtocol) {
        self.user = user
        self.workoutCompletionStore = workoutCompletionStore
    }

    init(user: User) {
        self.user = user
        workoutCompletionStore = WorkoutCompletionDataStore(userId: user.userId)
    }
}

WorkoutCOmpletionStore 实现如下:

class WorkoutCompletionDataStore: ObservableObject, WorkoutCompletionDataStoreProtocol {
    @Published var workoutCompletions: [WorkoutCompletion] = []
    private let userId: String?
 
    [...]

 func get() {
        guard let userId = userId
        else {
            workoutCompletions = []
            return
        }

        let fullPath = String(format: path, userId)
        store.collection(fullPath)
            .addSnapshotListener { querySnapshot, error in
                if let error = error {
                    AnalyticsWrapper.logError(message: "Error getting worKoutCompletions", error: error)
                    return
                }

                self.workoutCompletions = querySnapshot?.documents.compactMap { document in
                    try? document.data(as: WorkoutCompletion.self)
                } ?? []
            }
    }
[...]
}

按预期调用快照侦听器。更新了锻炼完成列表(我正在删除和添加对象)。

我遇到的问题是,当 Firstore 更新触发时,WorkoutCompletionDataStore 更新其锻炼完成后,显示这些锻炼完成的视图不会更新。


struct HomeScreen: View {
    @ObservedObject var homeQueryData: HomeQueryData
    @AppStorage("didShowOnboarding") var didShowOnboarding: Bool = false
    @EnvironmentObject var signedInAuthentication: SignedInAuthentication


    func startChat() {
        let controller = UIApplication.shared.windows.filter { $0.isKeyWindow }.first?.rootViewController
        Freshchat.sharedInstance().showConversations(controller!)
    }

    var body: some View {
        var workoutCompletions = signedInAuthentication.workoutCompletionStore.workoutCompletions
    [...]
}

我错过了什么?

4

1 回答 1

0

感谢@workingdog,我重构了我的代码,使 WorkoutCompletionDataStore 成为顶级环境对象,它现在可以工作了。

嵌套 Observable 对象似乎不起作用。

于 2021-11-28T14:46:51.240 回答