完成 Combine 后如何再次订阅?
How can I subscribe again after finishing with Combine?
订阅后,我用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")
输出结果如下
Received value: test1
Received completion: finished
Received completion: finished
如何获取“接收值:test2”?
它是 rx 编程的概念,并不特定于 combine。我建议你学习基础。 https://rxmarbles.com
当您收到完成事件或错误事件时,流就结束了它的生命。之后不会再有活动了。
你可以想象这就像流的死亡。不要让它死去或诞生新的来取代它。
发送完成后,发布者就完成了。因此,如果您想再次订阅并获取新事件,您将需要该发布者的 新实例。
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")
订阅后,我用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")
输出结果如下
Received value: test1
Received completion: finished
Received completion: finished
如何获取“接收值:test2”?
它是 rx 编程的概念,并不特定于 combine。我建议你学习基础。 https://rxmarbles.com
当您收到完成事件或错误事件时,流就结束了它的生命。之后不会再有活动了。
你可以想象这就像流的死亡。不要让它死去或诞生新的来取代它。
发送完成后,发布者就完成了。因此,如果您想再次订阅并获取新事件,您将需要该发布者的 新实例。
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")