migrant
migrant

Reputation: 508

Why a Combine publisher can still emit values after it emits completion

Theoretically, in my opinion, a publisher will not emit values once it emits a completion event. It is true when I use publishers such as PassthroughSubject .

However, as the sample code below, I use a publisher like Just or [1, 2, 3].publisher and the first subscriber already receives a completion. But the second subscriber can still receive the value emitted and a completion event.

Am I misunderstanding something?

var subscriptions = Set<AnyCancellable>()

let publisher = Just(1) // or [1, 2, 3].publisher

publisher.sink {
    print($0)
} receiveValue: {
    print($0)
}
.store(in: &subscriptions)

publisher.sink {
    print($0)
} receiveValue: {
    print($0)
}
.store(in: &subscriptions)

The output in the console is:

1
finished
1
finished

Upvotes: 2

Views: 827

Answers (1)

Lou Franco
Lou Franco

Reputation: 89192

You are subscribing twice and each subscriber is getting the value and a completion.

Upvotes: 0

Related Questions