Created
October 10, 2019 21:09
-
-
Save eliotfowler/6f10e7e6b09a2c96062122bdccc19af8 to your computer and use it in GitHub Desktop.
Initial implementation of withLatestFrom for Combine
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
import Combine | |
var cancellables = [AnyCancellable]() | |
extension Publisher { | |
func withLatestFrom<A, P: Publisher>( | |
_ second: P | |
) -> AnyPublisher<A, Failure> where P.Output == A, P.Failure == Failure { | |
return second | |
.map { result -> AnyPublisher<A, Failure> in | |
self.map({ _ in result }).eraseToAnyPublisher() | |
}.switchToLatest().eraseToAnyPublisher() | |
} | |
} | |
let names = PassthroughSubject<String, Never>() | |
let blips = PassthroughSubject<Void, Never>() | |
print("Sending \"Alfred\"") | |
names.send("Alfred") | |
print("Sending \"Maggie\"") | |
names.send("Maggie") | |
blips.withLatestFrom(names) | |
.sink { name in | |
print("[\(name)]") | |
} | |
.store(in: &cancellables) | |
print("*BLIP*") | |
blips.send(()) // prints nothing | |
print("Sending \"Ploppo\"") | |
names.send("Ploppo") | |
print("*BLIP*") | |
blips.send(()) // prints "Ploppo" | |
print("Sending \"Blobbo\"") | |
names.send("Blobbo") | |
print("*BLIP*") | |
blips.send(()) // prints "Blobbo" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment