Skip to content

Instantly share code, notes, and snippets.

@eliotfowler
Created October 10, 2019 21:09
Show Gist options
  • Save eliotfowler/6f10e7e6b09a2c96062122bdccc19af8 to your computer and use it in GitHub Desktop.
Save eliotfowler/6f10e7e6b09a2c96062122bdccc19af8 to your computer and use it in GitHub Desktop.
Initial implementation of withLatestFrom for Combine
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