我目前正在尝试使用Apple的新Combine
框架,但对于发布者-订阅者模式有一个基本问题。
当您有一个MyClass
的类,如下所示:
class MyClass {
var a: String
var b: String
var c: String
var d: String
}
您想观察属性的变化(在我的例子中,使用swift的Combine
框架),有两种方法:
// Option 1 - Whenever anything changes, just send the whole object to all subscribers. They can take what they want
let objectWillChange = PassthroughSubject<MyClass, Never>()
// Option 2 - Create individual publishers for every property that's supposed to be observable. Other classes can subscribe to what they need.
let a_willChange = PassthroughSubject<String, Never>()
let b_willChange = PassthroughSubject<String, Never>()
let c_willChange = PassthroughSubject<String, Never>()
let d_willChange = PassthroughSubject<String, Never>()
这些方法的优点和缺点是什么?有性能差异吗?太多的出版商会使事情变慢吗?有预定的方法吗?还是完全取决于口味和情况?
谢谢!