Last active
April 10, 2021 21:19
-
-
Save jasdev/5b2d9d16ed7d14ba9232020e3432d4ab to your computer and use it in GitHub Desktop.
Composed implementation of `Publisher.withLatestFrom`’s that handled finished events.
This file contains hidden or 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