2个重要的Subject
Subjects 是一种遵循 Subject 协议的特殊的发布者。
这个协议要求subjects
有一个 .send(_:)
方法,来允许开发者发送特定的值给订阅者或管道。
Combine 中有两种内建的 subject : CurrentValueSubject 和 PassthroughSubject。
Example 1
PassthroughSubject的订阅者无法接收之前的消息
let relay = PassthroughSubject<String, Never>()
relay.send("Hello")
relay.send("World!")
let subscription = relay
.sink { value in
print("subscription1 received value: \(value)")
}
//relay.send("Hello")
//relay.send("World!")
//: 之前发送的2条消息无法被subscription接收
Example 2
发送新的subject给发布者,之前定义的subscription即可接收到消息
let publisher = ["Here","we","go!"].publisher
publisher.subscribe(relay)
输出:
subscription1 received value: Here
subscription1 received value: we
subscription1 received value: go!
Example 3
CurrentValueSubject
发送的消息无论早晚都会全部发送给订阅者
let variable = CurrentValueSubject<String, Never>("")
variable.send("Initial text")
let subscription2 = variable.sink { value in
print("subscription2 received value: \(value)")
}
variable.send("More text")
输出:
subscription2 received value: Initial text
subscription2 received value: More text