another.im-ios/ConversationsClassic/AppData/Stores/RostersStore.swift
2024-08-11 13:39:17 +02:00

38 lines
1.3 KiB
Swift

import Combine
import Foundation
import GRDB
@MainActor
final class RostersStore: ObservableObject {
@Published private(set) var rosters: [Roster] = []
private var cancellable: AnyCancellable?
init(clientsPublisher: Published<[Client]>.Publisher) {
subscribeToClientsStore(clientsPublisher: clientsPublisher)
}
private func subscribeToClientsStore(clientsPublisher: Published<[Client]>.Publisher) {
let rostersPublisher = ValueObservation.tracking(Roster.fetchAll)
.publisher(in: Database.shared.dbQueue)
.receive(on: DispatchQueue.main)
.catch { _ in Just([]) }
cancellable = clientsPublisher
.flatMap { clients in
Publishers.MergeMany(clients.map { $0.$state })
.prepend(clients.map { $0.state })
.collect()
}
.combineLatest(rostersPublisher)
.sink { [weak self] clientStates, rosters in
self?.handleUpdates(clientStates: clientStates, rosters: rosters)
}
}
private func handleUpdates(clientStates: [ClientState], rosters: [Roster]) {
self.rosters = rosters
print("Client States: \(clientStates.count), Rosters: \(rosters.count)")
}
}