【发布时间】:2021-08-27 18:20:35
【问题描述】:
鉴于@OberservableObjects 的层次结构 - 我经常发现自己需要一个发布者来提供整个结构的某种更新聚合(下面的示例计算一个总和,但它可以是任何东西)
以下是我想出的解决方案 - 有点工作,但也不是...... :)
问题 #1:它看起来很复杂 - 我觉得我错过了一些东西......
问题 #2:它不起作用,因为顶部的 $foo 发布者确实在 foo 更改之前向 foo 发出更改,然后第二个 self.$foo 发布者中不存在这些更改(显示旧状态)。
有时我需要聚合与 swiftUI 视图更新同步 - 这样我就需要使用 @Published 值,而不需要在变量的 didSet 期间发出单独的发布者。
我没有找到好的解决方案...那么你们将如何解决这个问题?
class Foo:ObservableObject {
@Published var bar:Int = 0
}
class Foobar:ObservableObject {
@Published var foo:[Foo] = []
var sumPublisher:AnyPublisher<Int,Never> {
// Whenever the foo array or one of the foo.bar values change
//
$foo
.map { fooArray in
Publishers.MergeMany( fooArray.map { foo in foo.$bar } )
}
.switchToLatest()
// Calclulate a new sum by collecting and reducing all foo.bar values.
//
.map { [unowned self] _ in
self.$foo // <--- in case of a foo change, this is still the unchanged foo, therefore not correct.
.map { fooArray -> AnyPublisher<Int,Never> in
Publishers.MergeMany( fooArray.map { foo in foo.$bar.first() } )
.collect()
.map { barArray -> Int in
barArray.reduce(0, { $0 + $1 })
}
.eraseToAnyPublisher()
}
.switchToLatest()
}
.switchToLatest()
.removeDuplicates()
.eraseToAnyPublisher()
}
}
【问题讨论】: