当我记得一个类可以订阅另一个类的变化时,我找到了一个解决方案Combine
。因此,如果我可以让RoleStore
班级订阅 中的更改SkillStore
,那么RoleStore
可以在用户删除技能时更新和删除其角色中的技能。
为此,RolesStore
需要参考SkillStore
:
import SwiftUI
import PlaygroundSupport
var skillStore = SkillStore(skills: MySkills.skills())
var roleStore = RoleStore(roles: MyRoles.roles(), skillStore: skillStore)
struct ModelsView: View {
@ObservedObject var skillStore: SkillStore
@ObservedObject var roleStore: RoleStore
....
SkillStore
更新为PassthroughSubject
将发送已删除的技能 ( deletedPublisher
):
import Foundation
import Combine
public final class SkillStore: ObservableObject {
@Published public var skills: [Skill] = [] {
didSet {
let oldSkills = Set(oldValue)
let uniqueSet = oldSkills.subtracting(self.skills)
if let deletedSkill = uniqueSet.first {
deletedPublisher.send(deletedSkill)
}
}
}
private var cancellables: Set<AnyCancellable> = []
let deletedPublisher = PassthroughSubject<Skill, Never>()
public init(skills: [Skill]) {
self.skills = skills
}
public func delete(skills: [Skill]) {
for skill in skills {
if let index = self.skills.firstIndex(where: { $0 == skill }) {
self.skills.remove(at: index)
}
}
}
}
最后RoleStore
从所有具有该技能的角色中删除已删除的技能:
import Foundation
import Combine
import SwiftUI
public final class RoleStore: ObservableObject {
@Published public var roles: [Role] = []
@ObservedObject var skillStore: SkillStore
private var cancellables: Set<AnyCancellable> = []
public init(roles: [Role], skillStore: SkillStore) {
self.roles = roles
self.skillStore = skillStore
self.skillStore.deletedPublisher.sink { skill in
for roleIndex in self.roles.indices {
let skills = self.roles[roleIndex].skills.filter { $0 != skill }
self.roles[roleIndex].skills = skills
}
}
.store(in: &cancellables)
}
}
我已经用这些更改更新了 Playground。