类型
1. PassthroughSubject
let passthroughSubject = PassthroughSubject<String, Never>()
// 作为 Publisher 发送事件
passthroughSubject.send("Hello")
// 作为 Subscriber 订阅事件
passthroughSubject
.sink { value in
print("Received: \(value)")
}
.store(in: &cancellables)2. CurrentValueSubject
let currentValueSubject = CurrentValueSubject<String, Never>("Initial Value")
// 作为 Publisher 发送事件
currentValueSubject.send("Updated Value")
// 作为 Subscriber 订阅事件
currentValueSubject
.sink { value in
print("Received: \(value)")
}
.store(in: &cancellables)
// 可以访问当前值
print(currentValueSubject.value) // "Updated Value"3. ReplaySubject (通过自定义实现)
4. AnyPublisher
总结:
Last updated