Unable to do a urlSession request with Combine - swift

Unable to get Data using Combine, nothing is printed on the console.
struct RepositoryElement: Codable {}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://api.github.com/users/brunosilva808/repos")!
let repos = URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: [Repository].self, decoder: JSONDecoder())
.sink(receiveCompletion: { completion in // 5
print(completion)
}, receiveValue: { repositories in
print("brunosilva808 has \(repositories.count) repositories")
})
}
}

It's not working because your repo variable is going out of scope and thus your network request is being cancelled. You need to hold on to your request so make a variable in your ViewController to keep hold of it.
If you do something like this then it should work. You'll need to import Combine because AnyCancellable is part of Combine.
import Combine
class ViewController: UIViewController {
var cancellable: AnyCancellable?
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://api.github.com/users/brunosilva808/repos")!
cancellable = URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: [Repository].self, decoder: JSONDecoder())
.sink(receiveCompletion: { completion in // 5
print(completion)
}, receiveValue: { repositories in
print("brunosilva808 has \(repositories.count) repositories")
})
}
}
I couldn't check if it decodes properly because you didn't include the Repository struct.

Related

Reusable publishers (subscriptions?) in Combine

I've got a case where I'm using a dataTaskPublisher and then chaining the output, as shown below. Now I'm implementing a background download, using URLSession's downloadTask(with:completionHandler) and I need to perform the exact same operations.
So everything in the code, below, from the decode(type:decoder) onwards is common between both situations. Is there some way I can take a Data object and let it be passed through that same set of steps without duplicating the code?
anyCancellable = session.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: TideLowWaterHeightPredictions.self, decoder: Self.decoder)
.map { $0.predictions }
.eraseToAnyPublisher()
.sink {
...
} receiveValue: { predictions in
...
}
You can wrap it up in an extension:
extension Publisher where Output == Data {
func gargoyle() -> AnyCancellable {
return self
.decode(type: TideLowWaterHeightPredictions.self, decoder: Self.decoder)
.map { $0.predictions }
.sink {
...
} receiveValue: { predictions in
...
}
}
}
And use it like this:
session
.dataTaskPublisher(for: url)
.map { $0.data }
.gargoyle()
.store(in: &tickets)
Or like this if you already have a Data:
Just(data)
.gargoyle()
.store(in: &tickets)

Why aren't my Swift network requests working?

I've been trying out Swift/SwiftUI for the first time, so I decided to make a small Hacker News client. I seem to be able to get the list of ids of the top stories back fine, but once the dispatchGroup gets involved, nothing works. What am I doing wrong?
Data.swift
import SwiftUI
struct HNStory: Codable, Identifiable {
var id: UInt
var title: String
var score: UInt
}
class Fetch {
func getStory(id: Int, completion: #escaping (HNStory) -> ()) {
let url = URL(string: "https://hacker-news.firebaseio.com/v0/item/\(id).json")
URLSession.shared.dataTask(with: url!) { (data, _, _) in
let story = try!JSONDecoder().decode(HNStory.self, from: data!)
print(id, story)
DispatchQueue.main.async {
completion(story)
}
}
}
func getStories(completion: #escaping ([HNStory]) -> ()) {
let url = URL(string: "https://hacker-news.firebaseio.com/v0/topstories.json")
var stories: [HNStory] = []
print("here")
URLSession.shared.dataTask(with: url!) { (data, _, _) in
var ids = try!JSONDecoder().decode([Int].self, from: data!)
ids = Array(ids[0...10])
print(ids)
let dispatchGroup = DispatchGroup()
for id in ids {
dispatchGroup.enter()
self.getStory(id: id) { (story) in
stories.append(story)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
print("Completed work")
DispatchQueue.main.async {
completion(stories)
}
}
}.resume()
}
}
ContentView.swift (probably doesn't matter, but just in case)
import SwiftUI
struct ContentView: View {
#State private var stories: [HNStory] = []
var body: some View {
Text("Hacker News").font(.headline)
List(stories) { story in
VStack {
Text(story.title)
Text(story.score.description)
}
}.onAppear{
Fetch().getStories { (stories) in
self.stories = stories
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
One major problem is this line:
Fetch().getStories...
Networking takes time. You make a Fetch instance and immediately let it destroy itself. Thus it does not survive long enough to do any networking! You need to configure a singleton that persists.
Another problem, as OOPer points out in a comment, is that your getStory creates a data task but never tells it to resume — so that method is doing no networking at all, even if it did have time to do so.
FWIW, with Swift UI, I would suggest you consider using Combine publishers for your network requests.
So, the publisher to get a single story:
func storyUrl(for id: Int) -> URL {
URL(string: "https://hacker-news.firebaseio.com/v0/item/\(id).json")!
}
func hackerNewsStoryPublisher(for identifier: Int) -> AnyPublisher<HNStory, Error> {
URLSession.shared.dataTaskPublisher(for: storyUrl(for: identifier))
.map(\.data)
.decode(type: HNStory.self, decoder: decoder)
.eraseToAnyPublisher()
}
And a publisher for a sequence of the above:
func hackerNewsIdsPublisher(for ids: [Int]) -> AnyPublisher<HNStory, Error> {
Publishers.Sequence(sequence: ids.map { hackerNewsStoryPublisher(for: $0) })
.flatMap(maxPublishers: .max(4)) { $0 }
.eraseToAnyPublisher()
}
Note, the above constrains it to four at a time, enjoying the performance gains of concurrency, but limiting it so you do not risk having latter requests time out:
Anyway, here is the first fetch of the array of ids and then launching the above:
let mainUrl = URL(string: "https://hacker-news.firebaseio.com/v0/topstories.json")!
func hackerNewsPublisher() -> AnyPublisher<HNStory, Error> {
URLSession.shared.dataTaskPublisher(for: mainUrl)
.map(\.data)
.decode(type: [Int].self, decoder: decoder)
.flatMap { self.hackerNewsIdsPublisher(for: $0) }
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
(Now, you could probably cram all of the above into a single publisher, but I like to keep them small, so each individual publisher is very easy to reason about.)
So, pulling that all together, you have a view model like so:
import Combine
struct HNStory: Codable, Identifiable {
var id: UInt
var title: String
var score: UInt
}
class ViewModel: ObservableObject {
#Published var stories: [HNStory] = []
private let networkManager = NetworkManager()
private var request: AnyCancellable?
func fetch() {
request = networkManager.hackerNewsPublisher().sink { completion in
if case .failure(let error) = completion {
print(error)
}
} receiveValue: {
self.stories.append($0)
}
}
}
class NetworkManager {
private let decoder = JSONDecoder()
let mainUrl = URL(string: "https://hacker-news.firebaseio.com/v0/topstories.json")!
func storyUrl(for id: Int) -> URL {
URL(string: "https://hacker-news.firebaseio.com/v0/item/\(id).json")!
}
func hackerNewsPublisher() -> AnyPublisher<HNStory, Error> {
URLSession.shared.dataTaskPublisher(for: mainUrl)
.map(\.data)
.decode(type: [Int].self, decoder: decoder)
.flatMap { self.hackerNewsIdsPublisher(for: $0) }
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
// publisher for array of news stories, processing max of 4 at a time
func hackerNewsIdsPublisher(for ids: [Int]) -> AnyPublisher<HNStory, Error> {
Publishers.Sequence(sequence: ids.map { hackerNewsStoryPublisher(for: $0) })
.flatMap(maxPublishers: .max(4)) { $0 }
.eraseToAnyPublisher()
}
// publisher for single news story
func hackerNewsStoryPublisher(for identifier: Int) -> AnyPublisher<HNStory, Error> {
URLSession.shared.dataTaskPublisher(for: storyUrl(for: identifier))
.map(\.data)
.decode(type: HNStory.self, decoder: decoder)
.eraseToAnyPublisher()
}
}
And your main ContentView is:
struct ContentView: View {
#ObservedObject var viewModel = ViewModel()
var body: some View {
Text("Hacker News").font(.headline)
List(viewModel.stories) { story in
VStack {
Text(story.title)
Text(story.score.description)
}
}.onAppear {
viewModel.fetch()
}
}
}
By calling Fetch().getStories, the Fetch class goes out of scope immediately and isn't retained.
I'd recommend making Fetch an ObservableObject and setting it as a property on your view:
#StateObject var fetcher = Fetch()
Then, call:
fetcher.getStories {
self.stories = stories
}
If you wanted to get even more SwiftUI-ish with it, you may want to look into #Published properties on ObservableObjects and how you can make your view respond to them automatically. By doing this, you could avoid having a #State variable on your view at all, not have to have a callback function, and instead just load the stories into a #Published property on the ObservableObject. Your view will be re-rendered when the #Published property changes. More reading: https://www.hackingwithswift.com/quick-start/swiftui/observable-objects-environment-objects-and-published

Combine SwiftUI Remote Fetch Data - ObjectBinding doesn't update view

I am trying to learn Combine and it is a PITA for me. I never learned RX Swift, so this is all new to me. I am sure I am missing something simple with this one, but hoping for some help.
I am trying to fetch some JSON from an API and load it in a List view. I have a view model that conforms to ObservableObject and updates a #Published property which is an array. I use that VM to load my list, but it looks like the view loads way before this API returns (List showing up blank). I was hoping these property wrappers would do what I thought they were supposed to and re-render the view whenever the object changed.
Like I said, I am sure I am missing something simple. If you can spot it, I would love the help. Thanks!
class PhotosViewModel: ObservableObject {
var cancellable: AnyCancellable?
#Published var photos = Photos()
func load(user collection: String) {
guard let url = URL(string: "https://api.unsplash.com/users/\(collection)/collections?client_id=\(Keys.unsplashAPIKey)") else {
return
}
cancellable = URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: Photos.self, decoder: JSONDecoder())
.replaceError(with: defaultPhotosObject)
.receive(on: RunLoop.main)
.assign(to: \.photos, on: self)
}
}
struct PhotoListView: View {
#EnvironmentObject var photosViewModel: PhotosViewModel
var body: some View {
NavigationView {
List(photosViewModel.photos) { photo in
NavigationLink(destination: PhotoDetailView(photo)) {
PhotoRow(photo)
}
}.navigationBarTitle("Photos")
}
}
}
struct PhotoRow: View {
var photo: Photo
init(_ photo: Photo) {
self.photo = photo
}
var body: some View {
HStack {
ThumbnailImageLoadingView(photo.coverPhoto.urls.thumb)
VStack(alignment: .leading) {
Text(photo.title)
.font(.headline)
Text(photo.user.firstName)
.font(.body)
}
.padding(.leading, 5)
}
.padding(5)
}
}
Based on your updated solution, here are some improvement suggestions (that wont fit in a comment).
PhotosViewModel improvement suggestions
Might I just make the recommendation of changing your load function from returning Void (i.e. returning nothing), to be returning AnyPublisher<Photos, Never> and skipping the last step .assign(to:on:).
One advantage of this is that your code takes one step toward being testable.
Instead of replaceError with some default value you can use catch together with Empty(completeImmediately: <TRUE/FALSE>). Because is it always possible to come up with any relevant default value? Maybe in this case? Maybe "empty photos"? If so then you can either make Photos conform to ExpressibleByArrayLiteral and use replaceError(with: []) or you can create a static var named empty, allowing for replaceError(with: .empty).
To sum up my suggestions in a code block:
public class PhotosViewModel: ObservableObject {
#Published var photos = Photos()
// var cancellable: AnyCancellable? -> change to Set<AnyCancellable>
private var cancellables = Set<AnyCancellable>()
private let urlSession: URLSession
public init(urlSession: URLSession = .init()) {
self.urlSession = urlSession
}
}
private extension PhotosViewModel {}
func populatePhotoCollection(named nameOfPhotoCollection: String) {
fetchPhotoCollection(named: nameOfPhotoCollection)
.assign(to: \.photos, on: self)
.store(in: &cancellables)
}
func fetchPhotoCollection(named nameOfPhotoCollection: String) -> AnyPublisher<Photos, Never> {
func emptyPublisher(completeImmediately: Bool = true) -> AnyPublisher<Photos, Never> {
Empty<Photos, Never>(completeImmediately: completeImmediately).eraseToAnyPublisher()
}
// This really ought to be moved to some APIClient
guard let url = URL(string: "https://api.unsplash.com/users/\(collection)/collections?client_id=\(Keys.unsplashAPIKey)") else {
return emptyPublisher()
}
return urlSession.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: Photos.self, decoder: JSONDecoder())
.catch { error -> AnyPublisher<Photos, Never> in
print("☣️ error decoding: \(error)")
return emptyPublisher()
}
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
}
*Client suggestion
You might want to write some kind of HTTPClient/APIClient/RESTClient and take a look at HTTP Status codes.
This is a highly modular (and one might argue - overly engineered) solution using a DataFetcher and a DefaultHTTPClient conforming to a HTTPClient protocol:
DataFetcher
public final class DataFetcher {
private let dataFromRequest: (URLRequest) -> AnyPublisher<Data, HTTPError.NetworkingError>
public init(dataFromRequest: #escaping (URLRequest) -> AnyPublisher<Data, HTTPError.NetworkingError>) {
self.dataFromRequest = dataFromRequest
}
}
public extension DataFetcher {
func fetchData(request: URLRequest) -> AnyPublisher<Data, HTTPError.NetworkingError> {
dataFromRequest(request)
}
}
// MARK: Convenience init
public extension DataFetcher {
static func urlResponse(
errorMessageFromDataMapper: ErrorMessageFromDataMapper,
headerInterceptor: (([AnyHashable: Any]) -> Void)?,
badStatusCodeInterceptor: ((UInt) -> Void)?,
_ dataAndUrlResponsePublisher: #escaping (URLRequest) -> AnyPublisher<(data: Data, response: URLResponse), URLError>
) -> DataFetcher {
DataFetcher { request in
dataAndUrlResponsePublisher(request)
.mapError { HTTPError.NetworkingError.urlError($0) }
.tryMap { data, response -> Data in
guard let httpResponse = response as? HTTPURLResponse else {
throw HTTPError.NetworkingError.invalidServerResponse(response)
}
headerInterceptor?(httpResponse.allHeaderFields)
guard case 200...299 = httpResponse.statusCode else {
badStatusCodeInterceptor?(UInt(httpResponse.statusCode))
let dataAsErrorMessage = errorMessageFromDataMapper.errorMessage(from: data) ?? "Failed to decode error from data"
print("⚠️ bad status code, error message: <\(dataAsErrorMessage)>, httpResponse: `\(httpResponse.debugDescription)`")
throw HTTPError.NetworkingError.invalidServerStatusCode(httpResponse.statusCode)
}
return data
}
.mapError { castOrKill(instance: $0, toType: HTTPError.NetworkingError.self) }
.eraseToAnyPublisher()
}
}
// MARK: From URLSession
static func usingURLSession(
errorMessageFromDataMapper: ErrorMessageFromDataMapper,
headerInterceptor: (([AnyHashable: Any]) -> Void)?,
badStatusCodeInterceptor: ((UInt) -> Void)?,
urlSession: URLSession = .shared
) -> DataFetcher {
.urlResponse(
errorMessageFromDataMapper: errorMessageFromDataMapper,
headerInterceptor: headerInterceptor,
badStatusCodeInterceptor: badStatusCodeInterceptor
) { urlSession.dataTaskPublisher(for: $0).eraseToAnyPublisher() }
}
}
HTTPClient
public final class DefaultHTTPClient {
public typealias Error = HTTPError
public let baseUrl: URL
private let jsonDecoder: JSONDecoder
private let dataFetcher: DataFetcher
private var cancellables = Set<AnyCancellable>()
public init(
baseURL: URL,
dataFetcher: DataFetcher,
jsonDecoder: JSONDecoder = .init()
) {
self.baseUrl = baseURL
self.dataFetcher = dataFetcher
self.jsonDecoder = jsonDecoder
}
}
// MARK: HTTPClient
public extension DefaultHTTPClient {
func perform(absoluteUrlRequest urlRequest: URLRequest) -> AnyPublisher<Data, HTTPError.NetworkingError> {
return Combine.Deferred {
return Future<Data, HTTPError.NetworkingError> { [weak self] promise in
guard let self = self else {
promise(.failure(.clientWasDeinitialized))
return
}
self.dataFetcher.fetchData(request: urlRequest)
.sink(
receiveCompletion: { completion in
guard case .failure(let error) = completion else { return }
promise(.failure(error))
},
receiveValue: { data in
promise(.success(data))
}
).store(in: &self.cancellables)
}
}.eraseToAnyPublisher()
}
func performRequest(pathRelativeToBase path: String) -> AnyPublisher<Data, HTTPError.NetworkingError> {
let url = URL(string: path, relativeTo: baseUrl)!
let urlRequest = URLRequest(url: url)
return perform(absoluteUrlRequest: urlRequest)
}
func fetch<D>(urlRequest: URLRequest, decodeAs: D.Type) -> AnyPublisher<D, HTTPError> where D: Decodable {
return perform(absoluteUrlRequest: urlRequest)
.mapError { print("☢️ got networking error: \($0)"); return castOrKill(instance: $0, toType: HTTPError.NetworkingError.self) }
.mapError { HTTPError.networkingError($0) }
.decode(type: D.self, decoder: self.jsonDecoder)
.mapError { print("☢️ 🚨 got decoding error: \($0)"); return castOrKill(instance: $0, toType: DecodingError.self) }
.mapError { Error.serializationError(.decodingError($0)) }
.eraseToAnyPublisher()
}
}
Helpers
public protocol ErrorMessageFromDataMapper {
func errorMessage(from data: Data) -> String?
}
public enum HTTPError: Swift.Error {
case failedToCreateRequest(String)
case networkingError(NetworkingError)
case serializationError(SerializationError)
}
public extension HTTPError {
enum NetworkingError: Swift.Error {
case urlError(URLError)
case invalidServerResponse(URLResponse)
case invalidServerStatusCode(Int)
case clientWasDeinitialized
}
enum SerializationError: Swift.Error {
case decodingError(DecodingError)
case inputDataNilOrZeroLength
case stringSerializationFailed(encoding: String.Encoding)
}
}
internal func castOrKill<T>(
instance anyInstance: Any,
toType expectedType: T.Type,
_ file: String = #file,
_ line: Int = #line
) -> T {
guard let instance = anyInstance as? T else {
let incorrectTypeString = String(describing: Mirror(reflecting: anyInstance).subjectType)
fatalError("Expected variable '\(anyInstance)' (type: '\(incorrectTypeString)') to be of type `\(expectedType)`, file: \(file), line:\(line)")
}
return instance
}
This ended up being an issue with my Codable struct not being set up properly. Once I added a default object in the .replaceError method instead of a blank array (Thanks #Asperi), I was able to see the decoding error and fix it. Works like a charm now!
Original:
func load(user collection: String) {
guard let url = URL(string: "https://api.unsplash.com/users/\(collection)/collections?client_id=\(Keys.unsplashAPIKey)") else {
return
}
cancellable = URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: Photos.self, decoder: JSONDecoder())
.replaceError(with: [])
.receive(on: RunLoop.main)
.assign(to: \.photos, on: self)
}
Updated:
func load(user collection: String) {
guard let url = URL(string: "https://api.unsplash.com/users/\(collection)/collections?client_id=\(Keys.unsplashAPIKey)") else {
return
}
cancellable = URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: Photos.self, decoder: JSONDecoder())
.replaceError(with: defaultPhotosObject)
.receive(on: RunLoop.main)
.assign(to: \.photos, on: self)
}

iOS13's Combine streams don't flow after operator using schedulers

iOS13's Combine streams of publishers don't appear to be flowing after operator using schedulers.
Here's my code:
import Foundation
import Combine
struct MyPublisher: Publisher {
typealias Output = Int
typealias Failure = Error
func receive<S>(subscriber: S) where S : Subscriber,
Failure == S.Failure,
Output == S.Input {
subscriber.receive(1)
print("called 1")
subscriber.receive(2)
print("called 2")
subscriber.receive(completion: .finished)
print("called finish")
}
}
MyPublisher()
// .receive(on: RunLoop.main) // If this line removed, it will be fine.
// .throttle(for: .milliseconds(1000), scheduler: RunLoop.main, latest: false)) // If this line removed, it will be fine.
// .debounce(for: .milliseconds(1000), scheduler: RunLoop.main)) // If this line removed, it will be fine.
// .delay(for: .milliseconds(1000), scheduler: DispatchQueue.main)) // If this line removed, it will be fine.
.print()
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
print("finished")
case .failure(let error):
print("error:\(error)")
}
}, receiveValue: { num in
print("\(num)")
})
I expected output to be
1
2
finished
but the actual output is nothing.
If I don't use receive or throttle or debounce or delay. The output will be fine.
Is it a bug or something wrong with my code?
I tried with Playground (Xcode 11 beta3).
Subscription:
I'm unsure of why it works in the case of a single thread but you should make sure to call received(subscription:) on the subscriber. If you do not need to handle the subscribers demands you can use Subscribers.empty:
struct MyPublisher: Publisher {
typealias Output = Int
typealias Failure = Never
func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input {
subscriber.receive(subscription: Subscriptions.empty)
_ = subscriber.receive(1)
Swift.print("called 1")
_ = subscriber.receive(2)
Swift.print("called 2")
_ = subscriber.receive(completion: .finished)
Swift.print("called finish")
}
}
AnyCancellable:
You should notice a warning:
Result of call to 'sink(receiveCompletion:receiveValue:)' is unused
That should appear since sink returns an AnyCancellable:
func sink(receiveCompletion: #escaping ((Subscribers.Completion<Self.Failure>) -> Void), receiveValue: #escaping ((Self.Output) -> Void)) -> AnyCancellable
Anything that returns an AnyCancellable will get canceled as soon as the AnyCancellable is deallocated.
My speculation is that if you are putting this on another thread, then when the end of the calling method is reached the cancellable will deallocate before the subscription is received. But when received on the current thread it seems to be executing just in time for the subscription and output to show. Most likely the cancellable is being deallocated when the current thread exits.
Use Cancellable
For example :
class ImageLoader: ObservableObject {
#Published var image: UIImage?
private var cancellable: AnyCancellable?
func fetchImages() {
guard let urlString = urlString,
let url = URL(string: urlString) else { return }
cancellable = URLSession.shared.dataTaskPublisher(for: url)
.map { UIImage(data: $0.data) }
.replaceError(with: nil)
.receive(on: DispatchQueue.main)
.sink { [weak self] in self?.image = $0 }
}
}
Use the underscore
You can pass the underscore to pass the warning. I've used the example from Naishta's answer.
For example
class ImageLoader: ObservableObject {
#Published var image: UIImage?
func fetchImages() {
guard let urlString = urlString,
let url = URL(string: urlString) else { return }
_ = URLSession.shared.dataTaskPublisher(for: url)
.map { UIImage(data: $0.data) }
.replaceError(with: nil)
.receive(on: DispatchQueue.main)
.sink { [weak self] in self?.image = $0 }
}
}

How can I loop over the output of a publisher with Combine?

I'm working on rewriting my Hacker News reader to use Combine more heavily. I'm have two functions which both return an AnyPublisher, one of them get's the ids of a bunch of HN stories from the server and the other one fetches a story by it's id. I'm not sure how I could loop over the results of fetchStoryIds, run fetchStory with the id and end up with an array of Story objects with Combine.
import Combine
import Foundation
struct HackerNewsService {
private var session = URLSession(configuration: .default)
static private var baseURL = "https://hacker-news.firebaseio.com/v0"
private func fetchStoryIds(feed: FeedType) -> AnyPublisher<[Int], Error> {
let url = URL(string: "\(HackerNewsService.baseURL)/\(feed.rawValue.lowercased())stories.json")!
return session.dataTaskPublisher(for: url)
.retry(1)
.map { $0.data }
.decode(type: [Int].self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
private func fetchStory(id: Int) -> AnyPublisher<Story, Error> {
let url = URL(string: "\(HackerNewsService.baseURL)/item/\(id).json")!
return session.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: Story.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
}
Before I started the rewrite, I used this code to loop over the ids and get the stories.
func fetchStories(feed: FeedType, completionHandler: #escaping ([Story]?, Error?) -> Void) {
fetchStoryIds(feed: feed) { (ids, error) in
guard error == nil else {
completionHandler(nil, error)
return
}
guard let ids = ids else {
completionHandler(nil, error)
return
}
let dispatchGroup = DispatchGroup()
var stories = [Story]()
for id in ids {
dispatchGroup.enter()
self.fetchStory(id: id) { (story, error) in
guard error == nil else {
dispatchGroup.leave()
return
}
guard let story = story else {
dispatchGroup.leave()
return
}
stories.append(story)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
completionHandler(stories, nil)
}
}
}
}
Hmm.. It doesn't look like there is a Publishers.ZipMany that accepts a collection of publishers, so instead I merged the stories and collected them instead. Ideally this would collect them in the correct order but I haven't tested that and the documentation is still somewhat sparse across Combine.
func fetchStories(feed: FeedType) -> AnyPublisher<[Story], Error> {
fetchStoryIds(feed: feed)
.flatMap { ids -> AnyPublisher<[Story], Error> in
let stories = ids.map { self.fetchStory(id: $0) }
return Publishers.MergeMany(stories)
.collect()
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
If you are open to external code this is a gist implementation of ZipMany that will preserve the order:
https://gist.github.com/mwahlig/725fe5e78e385093ba53e6f89028a41c
Although I would think that such a thing would exist in the framework.