After subscribing, I completed the subscription with the send method.
I subscribed again, but it's finished.
How can I subscribe again?
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")
The output result is as follows.
Received value: test1
Received completion: finished
Received completion: finished
How can I get "Received value: test2"?
Once you send a completion, the Publisher is done. So, if you want to subscribe again and get new events, you'll need a new instance of that 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")