Created
July 23, 2020 07:47
-
-
Save byaruhaf/f0c4737238c2be89e85ef4b503b80559 to your computer and use it in GitHub Desktop.
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 Combine | |
// MARK: - ClueElement | |
struct ClueElement: Codable { | |
let id: Int | |
let answer, question: String | |
let value: Int | |
let categoryID: Int | |
let category: Category | |
enum CodingKeys: String, CodingKey { | |
case id, answer, question, value | |
case categoryID = “category_id” | |
case category | |
} | |
} | |
// MARK: - Category | |
struct Category: Codable { | |
let id: Int | |
let title: String | |
let cluesCount: Int | |
enum CodingKeys: String, CodingKey { | |
case id, title | |
case cluesCount = “clues_count” | |
} | |
} | |
enum HTTPError: LocalizedError { | |
case statusCode | |
case post | |
} | |
typealias Clue = [ClueElement] | |
var cancellable: AnyCancellable? | |
func loadData() { | |
let url1 = URL(string: “http://www.jservice.io/api/random”)! | |
cancellable = URLSession.shared.dataTaskPublisher(for: url1) | |
.map { $0.data } | |
.decode(type: Clue.self, decoder: JSONDecoder()) | |
.tryMap { category in | |
guard let categoryID = category.first?.categoryID else { throw HTTPError.post} | |
guard let cluesCount = category.first?.category.cluesCount else { throw HTTPError.post} | |
print(“\(categoryID)“) | |
return (categoryID,cluesCount) | |
} | |
.flatMap { (categoryID,cluesCount) in | |
return getClues(for: categoryID, cluesCount: cluesCount) | |
} | |
.receive(on: DispatchQueue.main) | |
.sink(receiveCompletion: { completion in | |
}) { clues in | |
print(clues) | |
} | |
} | |
func getClues(for id: Int, cluesCount: Int) -> AnyPublisher<Clue, Error> { | |
let url = URL(string: “http://www.jservice.io/api/clues?category=\(id)&offset=\(cluesCount - 4)“)! | |
print(url) | |
return URLSession.shared.dataTaskPublisher(for: url) | |
.map { $0.data } | |
.decode(type: Clue.self, decoder: JSONDecoder()) | |
.receive(on: DispatchQueue.main) | |
.eraseToAnyPublisher() | |
} | |
loadData() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment