[Combine]subscribe method

I know publisher has a method subscribe(_ subject: Subject)

let arrPublisher = [1,2,3,4].publisher
let tester = PassthroughSubject<Int, Never>()

arrPublisher.sink { result in
    print(result)
}.store(in: &subscriptions)
arrPublisher.subscribe(tester)
tester.send(5)

why tester as a subject cant send data after publisher has subscribed it.

As per the documentation of Sequence.publisher Apple Developer Documentation once the sequence of element is exhausted the publisher completes.

In your example you are trying to send a value after a completion event.

1 Like

@rpay_ios You use subscribe(_:) in order to connect a subject to a publisher in Combine like this:

let nameSubject = PassthroughSubject<String, Never>()
let namePublisher = ["Cosmin", "George", "Pupăză"].publisher
nameSubject.sink{print($0, terminator: "")}
nameSubject.send("My full name is")
namePublisher.map{" \($0)"}.subscribe(nameSubject)
nameSubject.send(".")

The above code prints My full name is Cosmin George Pupăză to the console. The period isn’t printed in this case because nameSubject completes once namePublisher does so it can’t send any other values because of that.

You can actually solve this in two different ways in Combine:

  1. Use sink(receiveValue:) for namePublisher like you do with nameSubject as follows:
nameSubject.sink{print($0, terminator: "")}
nameSubject.send("My full name is")
namePublisher.sink{print(" \($0)", terminator: "")}
nameSubject.send(".")
  1. Loop through the namePublisher sequence and send its values manually to nameSubject like this:
nameSubject.sink{print($0, terminator: "")}
nameSubject.send("My full name is")
for name in namePublisher.sequence {
  nameSubject.send(" \(name)")
}
nameSubject.send(".")

Both of the above solutions print My full name is Cosmin George Pupăză. to the console this time.

Please let me know if you have any questions or issues about the whole thing when you get a chance. Thank you!