Created
December 25, 2020 06:29
-
-
Save yycking/677d3451dc9780d5b4b6df248fc92d23 to your computer and use it in GitHub Desktop.
fetch all link from request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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