提问人:incelemeTRe 提问时间:12/25/2022 更新时间:12/25/2022 访问量:225
将 NotificationCenter 与 CurrentValueSubject 配合使用
Using NotificationCenter with CurrentValueSubject
问:
我是 Combine 的新手。我知道我们可以像这样使用 NotificationCenter 的组合实现发送值:
let myNotification = Notification.Name("myNotification")
class Cat {
var breed : String
init(breed: String) {
self.breed = breed
}
}
class ClassA {
var myCat = Cat(breed:"Ragdoll")
func sendNotification() {
NotificationCenter.default
.post(name: myNotification,
object: nil,
userInfo: ["cat": myCat])
}
}
class ClassB {
let cancellable = NotificationCenter.default
.publisher(for: myNotification).map ({ $0.userInfo!["cat"] as! Cat}).sink { cat in
print("My cat's breed is : \(cat.breed)")
}
}
let a = ClassA()
let b = ClassB()
a.sendNotification()
在这里,ClassB 不知道我会从 ClassA 获取数据,它只监听通知。
当我想使用CurrentValueSubject时:
class Cat {
var breed : String
init(breed: String) {
self.breed = breed
}
}
class ClassA {
let myCat : Cat = Cat(breed: "Ragdoll")
lazy var currentValueSubject = CurrentValueSubject<Cat, Never>(myCat)
func setMyCat() {
currentValueSubject.value = myCat
}
}
class ClassB {
let classA = ClassA()
var cancellables = [AnyCancellable]()
init(){
getMyCat()
}
func getMyCat() {
let _ = classA.currentValueSubject
.sink { cat in
print("My cat's breed: \(cat.breed)")
}.store(in: &cancellables)
}
}
let a = ClassA()
let b = ClassB()
a.setMyCat()
有没有办法创建 CurrentValueSubject 并通过 NotificationCenter 侦听它,以便接收者可以不知道发布者的来源?
我应该解雇 NotificationCenter.default.post......以第一种方法发布更改,但接收者对源无关。 它以第二种方法自动触发更改,无需发布任何内容,但接收者对发布者的来源并不不可知,因为我们必须说“classA.currentValueSubject....”
我想设置发布者(CurrentValueSubject 或 PassthroughSubject)并在 NotificationCenter 上订阅它,而不发布任何内容。
可能吗?
答:
1赞
vadian
12/25/2022
#1
CurrentValueSubject
和 of 是两个不同的 API。它们不可互换,但它们的行为非常相似。Publisher
NotificationCenter
- 为了能够订阅,您必须对主题有引用。调用或设置会发布一个值。
CurrentValueSubject
send()
value
- 的引用是其共享的 () 实例,发布通知会发布一个值。
NotificationCenter
default
评论
0赞
incelemeTRe
12/26/2022
好吧,那就没有办法那样使用它们了。谢谢
评论