Firstly, we created some publishers
let publisher = Publishers.Just("Combine Swift")
let sequencePublisher = let publisher = Publishers.Sequence(sequence: [1,2,3,5,6])
Call sink to subscribe to a publisher
let publisher = Publishers.Just("Combine Swift")
let subscribtion = publisher.sink { value in
print(value)
}
cancel the subscription
subscriber.cancel()
Subjects
let subject = PassthroughSubject<String, Never>()
let publisher = subject.eraseToAnyPublisher()
let subscriber = publisher.sink(receiveValue: { value in
print(value)
})
subject.send("Combine") //The Subscriber will print "Combine"
subject.send("Swift") //The Subscriber will print "Swift"
A subject can have multiple subscribers
let subject = PassthroughSubject<String, Never>()
let publisher = subject.eraseToAnyPublisher()
let subscriber1 = publisher.sink(receiveValue: { value in
print(value)
})
//subscriber1 will recive the events but not the subscriber2
subject.send("Event1")
subject.send("Event2")
let subscriber2 = publisher.sink(receiveValue: { value in
print(value)
})
//Subscriber1 and Subscriber2 will recive this event
subject.send("Event3")