Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Composed implementation of `Publisher.withLatestFrom`’s that handled finished events.
extension Publisher {
func withLatestFrom<Other: Publisher>(
_ other: Other
) -> AnyPublisher<Other.Output, Other.Failure>
where Failure == Other.Failure {
let upstream = share()
return other
.map { second in upstream.map { _ in second } }
.switchToLatest()
.zip(upstream) // `zip`ping and discarding `\.1` allows for
// upstream completions to be projected down immediately.
.map(\.0)
.eraseToAnyPublisher()
}
}
let first = PassthroughSubject<Int, Never>()
let second = PassthroughSubject<String, Never>()
var cancellables = Set<AnyCancellable>()
first
.withLatestFrom(second)
.sink(receiveCompletion: { print($0) }, receiveValue: { print($0) })
.store(in: &cancellables)
first.send(completion: .finished)
// Outputs:
//
// ```
// finished
// ```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment