我希望两个单独的ObjservableObject
共享一个@Published变量。
理想情况如下。由于Cannot assign to property: '$bar' is immutable
无法编译。如果对一个或另一个进行更改,我希望foo和bar保持同步。
class FooState: ObservableObject {
@Published var foo: Bool = false
}
class BarState: ObservableObject {
@Published var bar: Bool
init(fooState: FooState) {
self.$bar = fooState.$foo // compile error
}
}
let fooState = FooState()
let barState = BarState(fooState: fooState)
print(fooState.foo) // false
print(barState.bar) // false
fooState.foo = true
print(fooState.foo) // true
print(barState.bar) // true
答案 0 :(得分:0)
目前不支持此功能(我认为)。我知道解决该问题的唯一方法是自己订阅嵌套的可观察对象,并传播objectWillChange
事件:
class FooState: ObservableObject {
@Published var foo: Bool = false
}
class BarState: ObservableObject {
var fooState: FooState
var bar: Bool {
return self.fooState.foo
}
private var cancellables = Set<AnyCancellable>()
init(fooState: FooState) {
self.fooState = fooState
fooState.objectWillChange
.sink { [weak self] in
self?.objectWillChange.send()
}
.store(in: &cancellables)
}
}
let fooState = FooState()
let barState = BarState(fooState: fooState)
print(fooState.foo) // false
print(barState.bar) // false
fooState.foo = true
print(fooState.foo) // true
print(barState.bar) // true