订阅后,我使用send方法完成了订阅。
我又订阅了,但是已经看完了。我怎样才能再次订阅呢?
import Combine
let subject = PassthroughSubject<String, Never>()
subject
.sink(receiveCompletion: { completion in
print("Received completion:", completion)
}, receiveValue: { value in
print("Received value:", value)
})
subject.send("test1")
subject.send(completion: .finished)
subject
.sink(receiveCompletion: { completion in
print("Received completion:", completion)
}, receiveValue: { value in
print("Received value:", value)
})
subject.send("test2")
输出结果如下:
接收值:test1
接收完成:finished
接收完成:finished
如何获取"Received value: test2"?
发送完成后,Publisher就完成了。因此,如果你想再次订阅并获取新事件,你将需要该Publisher的新实例。
var subject = PassthroughSubject<String, Never>() //<-- var instead of let
subject
.sink(receiveCompletion: { completion in
print("Received completion:", completion)
}, receiveValue: { value in
print("Received value:", value)
})
subject.send("test1")
subject.send(completion: .finished)
subject = PassthroughSubject<String, Never>() //<-- Here
subject
.sink(receiveCompletion: { completion in
print("Received completion:", completion)
}, receiveValue: { value in
print("Received value:", value)
})
subject.send("test2")
这是rx编程的概念,不特定于组合。我建议你学习基本的。https://rxmarbles.com
当你收到一个完成事件或错误事件时,流就结束了它的生命周期。在那之后将不会有更多的事件。
你可以想象这就像小溪的死亡。不要让它死去,也不要让新的生命来代替它。