SwiftUI将@Published var从一个ObservableObject映射到另一个

时间:2020-08-26 16:40:33

标签: ios swift swiftui combine

我希望两个单独的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

1 个答案:

答案 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