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
20241214_WACATE2024冬_テスト設計技法をチョット俯瞰してみよう
kzsuzuki
3
440
LINEヤフーのフロントエンド組織・体制の紹介【24年12月】
lycorp_recruit_jp
0
530
KnowledgeBaseDocuments APIでベクトルインデックス管理を自動化する
iidaxs
1
260
ブラックフライデーで購入したPixel9で、Gemini Nanoを動かしてみた
marchin1989
1
520
新機能VPCリソースエンドポイント機能検証から得られた考察
duelist2020jp
0
220
Wantedly での Datadog 活用事例
bgpat
1
430
watsonx.ai Dojo #5 ファインチューニングとInstructLAB
oniak3ibm
PRO
0
160
サイボウズフロントエンドエキスパートチームについて / FrontendExpert Team
cybozuinsideout
PRO
5
38k
NW-JAWS #14 re:Invent 2024(予選落ち含)で 発表された推しアップデートについて
nagisa53
0
250
社外コミュニティで学び社内に活かす共に学ぶプロジェクトの実践/backlogworld2024
nishiuma
0
260
KubeCon NA 2024 Recap / Running WebAssembly (Wasm) Workloads Side-by-Side with Container Workloads
z63d
1
240
1等無人航空機操縦士一発試験 合格までの道のり ドローンミートアップ@大阪 2024/12/18
excdinc
0
150
Featured
See All Featured
Raft: Consensus for Rubyists
vanstee
137
6.7k
Building an army of robots
kneath
302
44k
Learning to Love Humans: Emotional Interface Design
aarron
273
40k
Writing Fast Ruby
sferik
628
61k
Designing Experiences People Love
moore
138
23k
Site-Speed That Sticks
csswizardry
2
190
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
47
5.1k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
247
1.3M
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
28
9.1k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
28
4.4k
Statistics for Hackers
jakevdp
796
220k
A Modern Web Designer's Workflow
chriscoyier
693
190k
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