TruMan1
TruMan1

Reputation: 36178

Fire last value when subscribing to publisher?

I have an AnyPublisher property that emits values. When someone subscribes to it, is there a way to emit the last value immediately and let it listen for future values from there?

Upvotes: 1

Views: 1166

Answers (1)

donnywals
donnywals

Reputation: 7601

You should use a CurrentValueSubject for this and erase that to AnyPublisher

let publisher = CurrentValueSubject<Int, Never>(1).eraseToAnyPublisher()
let c = publisher.sink(receiveValue: { int in 
  print(int)
})

The code above would immediately print 1 since that's the current value of the CurrentValueSubject.

Upvotes: 3

Related Questions