Search code examples
swiftreactive-programmingcombine

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?


Solution

  • 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.