Last active
February 5, 2021 15:26
-
-
Save IhwanID/02ec99fa85de0ec3b1930a6b8cbdfef0 to your computer and use it in GitHub Desktop.
Combine Many Merge Pokemon API
This file contains 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
// | |
// ViewController.swift | |
// Pokemon | |
// | |
// Created by Ihwan ID on 04/02/21. | |
// | |
import UIKit | |
import Combine | |
struct PokemonResponse: Codable{ | |
let results: [Pokemon] | |
} | |
struct Pokemon: Codable{ | |
let name: String | |
let url: String | |
} | |
struct PokemonDetailResponse: Codable{ | |
let id: Int | |
let name: String | |
let height: Int | |
let weight: Int | |
let types: [Types] | |
} | |
struct Types: Codable{ | |
let slot: Int | |
let type: Type | |
} | |
struct Type: Codable{ | |
let name: String | |
} | |
class ViewController: UIViewController { | |
private let urlString = "https://pokeapi.co/api/v2/pokemon/" | |
private var pokemonSubscriber: AnyCancellable? | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
self.pokemonSubscriber = URLSession.shared.dataTaskPublisher(for: URL(string: urlString)!) | |
.map{$0.data} | |
.decode(type: PokemonResponse.self, decoder: JSONDecoder()) | |
.tryMap { pokemons -> [String] in | |
return pokemons.results.map{$0.url} | |
} | |
.flatMap { urls in | |
return self.getFullData(input: urls) | |
} | |
.sink(receiveCompletion: { (completion) in | |
print(completion) | |
}, receiveValue: { (pokemons) in | |
for pokemon in pokemons{ | |
print("\(pokemon.name): \(pokemon.types.map{$0.type.name})") | |
} | |
}) | |
} | |
func createRequest(from id: String) -> AnyPublisher<PokemonDetailResponse, Error>{ | |
let url = URL(string: id)! | |
return URLSession.shared.dataTaskPublisher(for: url) | |
.map { $0.data } | |
.decode(type: PokemonDetailResponse.self, decoder: JSONDecoder()) | |
.receive(on: RunLoop.main) | |
.eraseToAnyPublisher() | |
} | |
func getFullData(input: [String]) -> AnyPublisher<[PokemonDetailResponse], Error>{ | |
let requests = input.compactMap { res in | |
return self.createRequest(from: res) | |
} | |
return Publishers.MergeMany(requests) | |
.compactMap { $0} | |
.collect() | |
.eraseToAnyPublisher() | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment