Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RxSwift x APIKit

USAMI Kosuke
September 30, 2015

RxSwift x APIKit

関西モバイルアプリ研究会 #6 - connpass
http://kanmoba.connpass.com/event/19592/

USAMI Kosuke

September 30, 2015
Tweet

More Decks by USAMI Kosuke

Other Decks in Programming

Transcript

  1. API ΫϥΠΞϯτ࣮૷ଆͷίʔυ protocol HogeAPIRequest: Request {} extension HogeAPIRequest { var

    baseURL: NSURL { return NSURL(...) } } struct HogeAPI { struct HogeRequest: HogeAPIRequest { typealias Response = HogeResponse } struct HogeResponse { ... } }
  2. API ΫϥΠΞϯτར༻ଆͷίʔυ let request = HogeAPI.HogeRequest(...) API.sendRequest(request) { result in

    switch result { case .Failure(let error): // ࣦഊ࣌ͷॲཧ case .Success(let response): // ੒ޭ࣌ͷॲཧ } }
  3. NSURLSession ͷ࣮૷Λࢀর͢Δ func rx_response(request: NSURLRequest) -> Observable<NSData!, NSURLResponse!> { return

    create { observer in // request Λૹ৴ͯ͠ϨεϙϯεΛड͚औΔ if ࣦഊ { observer.on(.Error(error)) } else { observer.on(.Next(data, response)) observer.on(.Completed) } return AnonymousDisposable { /* Ωϟϯηϧॲཧ */ } } }
  4. APIKit ൛ func responseFrom<T: AppAPIRequest>(request: T) -> Observable<T.Response> { return

    create { (observer: ObserverOf<T.Response>) in API.sendRequest(request) { result in switch result { case .Failure(let error): observer.on(.Error(error)) case .Success(let response): observer.on(.Next(response)) observer.on(.Completed) } } return AnonymousDisposable { API.cancelRequest(T) } } }
  5. ࢖͍ํ let request = HogeAPI.HogeRequest(...) HogeAPI.responseFrom(request) .subscribeOn(sessionScheduler) .map { (data,

    response) in // όοΫάϥ΢ϯυॲཧ } .observeOn(mainScheduler) .map { data in // UIॲཧ }
  6. ;Γ͔͑Γ 4 ؆୯ʹ࣮૷Ͱ͖ͨ 4 ศར 4 ͋ΕɺResult ܕͷҙຯ͸ʁ 4 Rx

    ͷ࣮૷ͷதͰ͔͠࢖ΘΕͳ͘ͳ͚ͬͨͲɾɾɾ 4 ΤϥʔϋϯυϦϯά͸ RxSwift Ͱ΍Ε͹͍͍