Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Moya+RxSwiftで実現する!ReactiveなAPIリクエスト
Search
satoshin21
October 02, 2017
Technology
0
3.1k
Moya+RxSwiftで実現する!ReactiveなAPIリクエスト
俺コン Vol.1 / Day. 1
https://orecon.connpass.com/event/63769/
satoshin21
October 02, 2017
Tweet
Share
More Decks by satoshin21
See All by satoshin21
少数精鋭で戦うための技術的改善について
satoshin21
3
1.1k
GTXiLibで小さく始めるAccessibility Testing
satoshin21
0
4.9k
iPhoneのカメラで写真撮影から現像までの技術を紐解く
satoshin21
4
3.2k
try! swift-sh
satoshin21
2
880
Reduxを取り入れて開発はpairs開発はどう変わったか
satoshin21
0
350
レガシーなアプリケーションの 60fps化を目指す為にやっていること
satoshin21
12
3.8k
Introducing CodeLayout with Tips
satoshin21
6
1.5k
World of No Interface Builder
satoshin21
0
1.8k
What I've done to attend WWDC
satoshin21
0
95
Other Decks in Technology
See All in Technology
Wvlet: A New Flow-Style Query Language For Functional Data Modeling and Interactive Data Analysis - Trino Summit 2024
xerial
1
120
終了の危機にあった15年続くWebサービスを全力で存続させる - phpcon2024
yositosi
9
7.7k
Jetpack Composeで始めるServer Cache State
ogaclejapan
2
170
Amazon Kendra GenAI Index 登場でどう変わる? 評価から学ぶ最適なRAG構成
naoki_0531
0
110
生成AIをより賢く エンジニアのための RAG入門 - Oracle AI Jam Session #20
kutsushitaneko
4
220
2024年にチャレンジしたことを振り返るぞ
mitchan
0
140
第3回Snowflake女子会_LT登壇資料(合成データ)_Taro_CCCMK
tarotaro0129
0
190
バクラクのドキュメント解析技術と実データにおける課題 / layerx-ccc-winter-2024
shimacos
2
1.1k
podman_update_2024-12
orimanabu
1
270
株式会社ログラス − エンジニア向け会社説明資料 / Loglass Comapany Deck for Engineer
loglass2019
3
32k
20241214_WACATE2024冬_テスト設計技法をチョット俯瞰してみよう
kzsuzuki
3
450
大幅アップデートされたRagas v0.2をキャッチアップ
os1ma
2
530
Featured
See All Featured
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
8
1.2k
Mobile First: as difficult as doing things right
swwweet
222
9k
Navigating Team Friction
lara
183
15k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
356
29k
Fontdeck: Realign not Redesign
paulrobertlloyd
82
5.3k
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
159
15k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
247
1.3M
Measuring & Analyzing Core Web Vitals
bluesmoon
4
170
The Pragmatic Product Professional
lauravandoore
32
6.3k
Fantastic passwords and where to find them - at NoRuKo
philnash
50
2.9k
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
6
520
Dealing with People You Can't Stand - Big Design 2015
cassininazir
365
25k
Transcript
Moya + RxSwi,Ͱ࣮ݱ͢Δʂ Reac%veͳAPIϦΫΤετ Զίϯ Vol.1 Day. 1 @satoshin21 @satoshin21
1
INTRODUCE • @satoshin21 • eureka, Inc. • Pairs JP iOS
Applica<on Engineer • created Chainable Anima<on Library "Anima" @satoshin21 2
@satoshin21 3
What's Moya? @satoshin21 4
Whats' Moya? • Network abstrac.on layer • RxSwi6, Reac.veSwi6ͱͷ࿈ܞ͕σϑΥϧτͰՄೳ •
encapsulates Alamofire • ϓϥάΠϯΛ࡞Մೳ • ίϛϡχςΟ͕׆ൃ ( ༷ʑͳExtension ) @satoshin21 5
How to implement Moya.TargetType public enum GitHub { case zen
case userProfile(String) case userRepositories(String) } @satoshin21 6
How to implement Moya.TargetType extension GitHub: TargetType { public var
baseURL: URL { return URL(string: "https://api.github.com")! } public var path: String { switch self { case .userProfile(let name): return "/users/\(name.urlEscaped)" ... } } public var method: Moya.Method = .get public var parameters: [String: Any]? { ... } } @satoshin21 7
How to request with RxSwi0 & Moya let githubProvider =
MoyaProvider<GitHub>() githubProvider.request(.userProfile("satoshin21")).subscribe { event in switch event { case let .next(response): let jsonString = try? response.mapString() message = jsonString ?? message case let .error(error): print(error) default: break } } @satoshin21 8
@satoshin21 9
That's it? @satoshin21 10
Sampleͷ՝ • enumʹTargetTypeΛ࣮ • ΤϯυϙΠϯτ͕૿͑Δͱࠈ • Observable<Moya.Response> • Response ParseΛຖߦ͏
• APIKitͷΑ͏ʹType SafeͰͳ͍ @satoshin21 11
ཧܗ DoSomething() .asDriver(onErrorJustReturn: nil) .drive(imageView.rx.image) .addDisposableTo(disposeBag) @satoshin21 12
Moya Customiza-on for Pairs(jp) • enum to struct • Type
safeͳObservable<E> • Type Erasure @satoshin21 13
@satoshin21 14
enum to struct enum API { } extension API {
enum Community {} } // Community API extension API.Community { /// ίϛϡχςΟใऔಘ struct GetSingle: PairsTargetType { ... } /// Search struct Search: PairsTargetType { ... } } @satoshin21 15
enum to struct let communitySearch = API.Community.Search() @satoshin21 16
PairsTargetType protocol PairsTargetType: TargetType, ObservableType { /// DecodedResponseType associatedtype D
/// ObservableType.EʹόΠϯυͤ͞ΔͨΊ associatedtype E /// Ϩεϙϯε͔ΒೝΊ͍ͯΔܗࣜσίʔυ͢ΔʢJSONͳͲʣ func decodeResponse(_ response: Moya.Response) throws -> D /// Ϩεϙϯεใ͔Βྃ·ͰͷObservableΛ࡞͢Δ func didDecodeData(_ responseData: D) -> Observable<E> } @satoshin21 17
implements PairsTargetType struct GetCampaign: PairsTargetType { // Moya.Response -> JSON
typealias D = JSON // JSON -> [Community] typealias E = [Community] func didDecodeData(_ responseData: JSON) -> Observable<[Community]> { // JSON͔Β[Community]ͷϚοϐϯάDBͷอଘͳͲ let communities = ... return communities } } @satoshin21 18
PairsTargetTypeͷObservableԽ extension PairsTargetType { func subscribe<O: ObserverType>(_ observer: O) ->
Disposable where O.E == E { // APIϦΫΤετ -> decodeResponse(response)ͰMoya.Response͔Βσίʔυ let requestData = Observable<D>.create { (observer) in let cancellable = API.provider.request(.init(target: self), completion: { (result) in switch result { case .success(let response): let responseData = try self.decodeResponse(response) observer.onNext(responseData) observer.onCompleted() } ) return Disposables.create(with: cancellable.cancel) } // σίʔυ͞ΕͨΦϒδΣΫτ(ओʹJSON)͔ΒϚοϐϯά͞ΕͨΦϒδΣΫτ return requestData .flatMap(self.didDecodeData) .subscribe(observer) } @satoshin21 19
RxMoyaProvider<AnyPairsTarget> extension API { fileprivate static let provider = API.Provider()
// PairsTargetTypeΛ࣮ͨ͠ϦΫΤετͷॲཧΛߦ͏ fileprivate class Provider: RxMoyaProvider<AnyPairsTarget> { init() { } } } @satoshin21 20
Binding API.Image.Get() .asDriver(onErrorJustReturn: nil) .drive(imageView.rx.image) .addDisposableTo(disposeBag) @satoshin21 21
How we use Moya in Pairs // ίϛϡχςΟͱΧςΰϦʔΛऔಘ Observable .zip(
API.Community.GetCommunities(), API.Community.GetCategories(), resultSelector: { $0 }) .subscribe( onNext: { (communities: [Community], categories: [Category]) in // do something! }).addDisposableTo(disposeBag) @satoshin21 22
Summary • Moyaࣗମڧྗ͕ͩɺΧελϚΠζͰΑΓReac)veʹ @satoshin21 23
@satoshin21 24