Hey I learned on an HackingWithSwift Tutorial How to make a chained network request with Combine (see code below). Now I will build the same logic with RXSwift but I don't know how can I get/subscribe like in Combine to get the end result.
Combine:
//Combine code
func fetch<T: Decodable>(_ url: URL, defaultValue: T) -> AnyPublisher<T, Never> {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return URLSession.shared.dataTaskPublisher(for: url)
.retry(1)
.map(\.data)
.decode(type: T.self, decoder: decoder)
.replaceError(with: defaultValue)
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
//call fetch method and get the end result
fetch(url, defaultValue: [URL]())
.flatMap { urls in
urls.publisher.flatMap { url in
fetch(url, defaultValue: [NewsItem]())
}
}
.collect()
.sink { values in
let allItems = values.joined()
items = allItems.sorted { $0.id > $1.id }
}
.store(in: &requests)
//RXSwift code
func fetchWithRX<T: Decodable>(_ url: URL, defaultValue: T) -> Observable<T> {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let request = URLRequest(url: url)
return URLSession.shared.rx.response(request: request)
.retry(1)
.map(\.data)
.decode(type: T.self, decoder: decoder)
.debug()
.catchAndReturn(defaultValue)
.observe(on: MainScheduler.instance)
}
//call fetch2 method
Now I want to subscribe to the values like in the first fetch method with flatMap..collect..sink etc.
fetchWithRX(url, defaultValue: [URL]())