Skip to content

Instantly share code, notes, and snippets.

@jasdev
Last active April 10, 2021 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasdev/5b2d9d16ed7d14ba9232020e3432d4ab to your computer and use it in GitHub Desktop.
Save jasdev/5b2d9d16ed7d14ba9232020e3432d4ab to your computer and use it in GitHub Desktop.
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