Skip to content

Instantly share code, notes, and snippets.

@yycking
Created December 25, 2020 06:29
Show Gist options
  • Save yycking/677d3451dc9780d5b4b6df248fc92d23 to your computer and use it in GitHub Desktop.
Save yycking/677d3451dc9780d5b4b6df248fc92d23 to your computer and use it in GitHub Desktop.
fetch all link from request
import Foundation
import PlaygroundSupport
import Combine
PlaygroundPage.current.needsIndefiniteExecution = true
enum RequestError: Error {
case sessionError(error: Error)
}
var cancellableSet: Set<AnyCancellable> = []
URLSession.shared.dataTaskPublisher(for: request)
.tryMap { $0.data }
.decode(type: APIStruct.self, decoder: JSONDecoder())
.map{ $0.Data.map{$0.thumb} }
.map{ links -> [AnyPublisher<(URL, String), Error>] in
links.map{ link in
URLSession.shared.dataTaskPublisher(for: link)
.map{$0.response.mimeType ?? ""}
.map{ (link, $0) }
.mapError { error -> RequestError in
return RequestError.sessionError(error: error)
}
.eraseToAnyPublisher()
}
}.flatMap{ tasks -> Publishers.MergeMany<AnyPublisher<(URL, String), Error>> in
Publishers.MergeMany(tasks)
}.collect()
.sink { result in
print("api: \(result)")
PlaygroundPage.current.finishExecution()
} receiveValue: { values in
var mimes = [String: Int]()
values.forEach{ value in
let link = value.0
let mime = value.1
print("\(link) is \(mime)")
var count = mimes[mime] ?? 0
count += 1
mimes[mime] = count
}
print("total: \(values.count)")
print(mimes)
}.store(in: &cancellableSet)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment