Composed implementation of `Publisher.withLatestFrom`’s that handled finished events.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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