Home > Blockchain >  How can I subscribe again after finishing with Combine?
How can I subscribe again after finishing with Combine?

Time:10-28

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"?

CodePudding user response:

It's concept of rx programming not specific to combine. I would recommend you to learn the basic. https://rxmarbles.com

When you received a completion event or an error event, the stream is end of it's life. There's will be no more events after those.

You can imagine it is like stream's death. Don't let it die or born new one to replace it.

CodePudding user response:

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")
  • Related