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

RxSwiftでエラーを分岐するTips

yimajo
November 15, 2018

 RxSwiftでエラーを分岐するTips

potatotips #56 での発表資料です

https://potatotips.connpass.com/event/104242/

yimajo

November 15, 2018
Tweet

More Decks by yimajo

Other Decks in Technology

Transcript

  1. ҟৗॲཧܥͷύλʔ ϯ͸৭ʑ  ΤϥʔΛΩϟονͯ͠PO&SSPSͱͯ͠ྲྀ͞ͳ͍Α͏ʹ͢Δ w DBUDI&SSPS\^ͯ͠Τϥʔʹରॲ w 0CTFSWBCMF3FTVMUͳܕͰྲྀ͢ w ͜͜Ͱͷ3FTVMU͸੒൱ͱͦͷ৘ใΛؚΉFOVN

     0CTFSWBCMFγʔέϯεΛ෼ذ͢Δ w 0CTFSWBCMF3FTVMUͳܕʹͨ͠΋ͷΛ͞Βʹͭͷγʔέϯεਖ਼ৗͱҟ ৗܥʹ෼ذ w ࢀߟϝϧΧϦΞοςͷ3Y4XJGU࣮૷ΨΠυIUUQTTQFBLFSEFDLDPNQBSBLFFUZ NFSVLBSJBUVUFGBMTFSYTXJGUTIJ[IVBOHHBJEP TMJEF
  2. ਖ਼ৗܥͱҟৗܥͷΠϕϯτΛ औΓग़ͤΔΑ͏ͳϝιουΛ༻ҙ extension ObservableType where E: EventConvertible { public func

    elements() -> Observable<E.ElementType> { return filter { $0.event.element != nil } .map { $0.event.element! } } public func errors() -> Observable<Swift.Error> { return filter { $0.event.error != nil } .map { $0.event.error! } } } // 1. Observable<E>ͷE͕EventConvertible४ڌͰ͋Ε͹࢖͑ΔΑ͏ʹͳΔ // ྫ͑͹ Observable<Event<E>> ͱ͔ // 2_1. Πϕϯτͷਖ਼ৗܥelementͷΈΛฦ͢Α͏ʹ͢Δ͚ͩ // 2_2. ΠϕϯτͷΤϥʔͷΈΛฦ͢Α͏ʹ͢Δ͚ͩ
  3. let result = Observable.of(1, 2) .flatMap { _ -> Observable<Event<String>>

    in let observable = Observable<String>.create { observer in observer.onNext("A") observer.onError(TestError.test) observer.onNext(“B") observer.onCompleted() return Disposables.create() } return observable.materialize() } output1 = result .elements() .subscribe(onNext: { print("elements, onNext: \($0)”) }, onError: { print("elements, onError: \($0)") },) error = result .errors() .subscribe(onNext: { print("errors, onNext: \($0)") }, onError: { print("errors, onError: \($0)") }) —— ग़ྗ —— elements, onNext: A elements, onNext: A elements, onCompleted: errors, onNext: test errors, onNext: test errors, onCompleted:
  4. ྫಛఆͷΤϥʔʹ͢Δ let error: Observable<OAuthSwiftError> = result .errors() .map { guard

    let error = $0 as? OAuthSwiftError else { // ͜͜ͰΫϥογϡϨϙʔτૹΓͭͭ …. fatalError($0.localizedDescription) } return error } .share(replay: 1) w Ͱ͖Δ͚Ͳ΋ʜ w ΍Δඞཁ͕͋ΔͱࢥͬͨΒ΍ͬͨΒΑΖͦ͠͏ w .PEFM૚ͷԞਂ͘ͰಛఆͷΤϥʔͷΈΛ૝ఆ͍ͯ͠Δ৔߹ͳͲ w ͦ͜·Ͱ΍Δඞཁͳͦ͞͏ͱ൑அͰ͖Δͱ͖ w 7JFX.PEFMͷϓϨθϯςʔγϣϯϩδοΫͰ&SSPS൑ผ͢Ε͹͍ ͍ͱ͍͏৔߹ͳͲ
  5. 3Y4XJGU&YU IUUQTHJUIVCDPN3Y4XJGU$PNNVOJUZ3Y4XJGU&YU w FMFNFOUT FSSPST  w VOXSBQ  w

    JHOPSF @WBMVFT5P*HOPSF&ʜ  w OPU  w pMUFS.BQ\^ FUD