conversations-classic-ios/ConversationsClassic/AppData/Stores/RostersStore.swift

38 lines
1.3 KiB
Swift
Raw Normal View History

2024-08-11 00:28:01 +00:00
import Combine
import Foundation
import GRDB
@MainActor
final class RostersStore: ObservableObject {
@Published private(set) var rosters: [Roster] = []
2024-08-11 11:39:17 +00:00
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)")
2024-08-11 00:28:01 +00:00
}
}