0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RxSwiftでジェネリクスを使ってAPIをたたく備忘録

Posted at

コード

本記事は備忘録なので説明はほとんどなしです。
なので早速コードです。

import Foundation
import RxSwift
import Alamofire

protocol APIServiceProtocol {
    func excute<T: Codable>(urlString: String) -> Single<T>
}

class APIService: APIServiceProtocol {
    
    func excute<T: Codable>(urlString: String) -> Single<T> {
        Single<T>.create { (single) -> Disposable in
            
            let url = URL(string: urlString)!
            AF.request(url).response { (response) in
                guard let data = response.data else {
                    return
                }
                
                do {
                    let decodedData = try JSONDecoder().decode(T.self, from: data)
                    single(.success(decodedData))
                } catch {
                    single(.failure(error))
                }
            }
            
            return Disposables.create()
        }
    }
}

こんな感じです。
何気にジェネリクスを利用したのはじめてなんですがTにたいして配列もいけるんですね

呼び出しがわ

let qiita: Single<[QiitaModel]> = apiService.excute(urlString: "https://qiita.com/api/v2/items")
        
        qiita.asObservable().bind(to: tableView.rx.items) { tableView, row, model in
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
            cell.textLabel?.text = model.title
            cell.detailTextLabel?.text = model.user.name
            return cell
        }.disposed(by: disposeBag)

qiitaAPIを叩いています。
一行目が一番大事です。
型を明示してあげないといけないので一行目なしだとエラーが吐かれます

以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?