Example:
class Demo5 {
var cancellables = Set<AnyCancellable>()
func example(of: String) {
let pub1 = PassthroughSubject<Int, Never>()
let pub2 = PassthroughSubject<Int, Never>()
let pub3 = PassthroughSubject<Int, Never>()
let publishers = PassthroughSubject<PassthroughSubject<Int, Never>, Never>()
publishers
.switchToLatest()
.sink(receiveCompletion: { _ in print("Completed!") },
receiveValue: { print($0) })
.store(in: &cancellables)
publishers.send(pub1)
pub1.send(1)
pub1.send(2)
publishers.send(pub2)
pub1.send(3)
pub2.send(4)
pub2.send(5)
publishers.send(pub3)
pub2.send(6)
pub3.send(7)
pub3.send(8)
pub3.send(9)
pub3.send(completion: .finished)
publishers.send(completion: .finished)
}
}
let d = Demo5()
d.example(of: "good")
Example 2 (Apple Official):
let pub = PassthroughSubject<Int, Never>()
let cancellable = pub
.setFailureType(to: URLError.self)
.map() { index -> URLSession.DataTaskPublisher in
let url = URL(string: "https://example.org/get?index=\(index)")!
return URLSession.shared.dataTaskPublisher(for: url)
}
.switchToLatest()
.sink(receiveCompletion: { print("Complete: \($0)") },
receiveValue: { (data, response) in
guard let url = response.url else {
print("Bad response."); return
}
print("URL: \(url)")
})
for i in 1...5 {
DispatchQueue.main.asyncAfter(deadline: .now() + TimeInterval(i/10)) {
pub.send(i)
}
}
Example 3: This example will give you an idea of switchToLatest
from a different angle.
struct Feedback<State, Event> {
let run: (AnyPublisher<State, Never>) -> AnyPublisher<Event, Never>
}
extension Feedback {
init<Effect: Publisher>
(effects: @escaping (State) -> (Effect))
where Effect.Output == Event, Effect.Failure == Never
{
self.run = { statePub -> AnyPublisher<Event, Never> in
statePub
.map { effects($0) } // Effect Publisher<Event, Never>
.switchToLatest() // Event
.eraseToAnyPublisher() // AnyPublisher<Event, Never>
}
}
}