Just("Hello Combine") creates a publisher, it's the source of data. This specific one just emits one single value and then finishes. Think of it as someone who has data and is ready to send it.
handleEvents is just sitting in the middle of the pipeline observing whats happening, it's not doing anything to the data it's just logging "hey a subscriber just attached" so you can see the sequence of events. It's purely for debugging purposes here.
sink is the subscriber, this is the end of the pipeline where you actually receive the data. It has two callbacks, receiveValue which gives you the actual value that was emitted, and receiveCompletion which tells you the publisher is done or errored out.
.store(in: &cancellables) — when sink subscribes it hands back a token called AnyCancellable. If nobody holds onto that token the subscription dies immediately. So you store it in cancellables which is a set that lives on the view controller, keeping the subscription alive for as long as the view controller is alive. When the view controller dies the set dies, the token dies, and the subscription gets cleanly cancelled.
So the flow is simply — publisher emits value → flows through the pipeline → subscriber receives it → subscription stays alive because the token is stored.
Combine is Apple’s reactive programming framework used to handle asynchronous streams of values over time.
Instead of manually handling callbacks, Combine allows data to flow through a pipeline consisting of:
Publisher → Operators → Subscriber
The publisher produces values, operators transform those values, and the subscriber receives them.
A Combine pipeline describes how data flows from the source to the receiver.
Conceptually:
Publisher (source of data)
↓
Operators (optional transformations)
↓
Subscriber (receives values)
This pattern is the core architecture of Combine.
let publisher = Just("Hello Combine")
publisher
.handleEvents(receiveSubscription: { _ in
print("Subscriber attached")
})
.sink(
receiveCompletion: { completion in
print("Completion:", completion)
},
receiveValue: { value in
print("Received:", value)
}
)
.store(in: &cancellables)