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
3k
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
850
Reduxを取り入れて開発はpairs開発はどう変わったか
satoshin21
0
340
レガシーなアプリケーションの 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
90
Other Decks in Technology
See All in Technology
音声×Copilot オンコパの世界
kasada
1
120
【令和最新版】AWS Direct Connectと愉快なGWたちのおさらい
minorun365
PRO
5
630
Oracle Cloud Infrastructureデータベース・クラウド:各バージョンのサポート期間
oracle4engineer
PRO
28
12k
なぜ今 AI Agent なのか _近藤憲児
kenjikondobai
2
1.2k
利きプロセススケジューラ
sat
PRO
5
2.7k
rootlessコンテナのすゝめ - 研究室サーバーでもできる安全なコンテナ管理
kitsuya0828
1
160
SREの組織類型に応じた リーダシップの考察
kenta_hi
PRO
1
640
私はこうやってマインドマップでテストすることを出す!
mineo_matsuya
0
310
今、始める、第一歩。 / Your first step
yahonda
2
730
Redmine 6.0 新機能評価ガイド
vividtone
0
310
Amazon CloudWatch Network Monitor のススメ
yuki_ink
0
160
Railsで4GBのデカ動画ファイルのアップロードと配信、どう実現する?
asflash8
2
270
Featured
See All Featured
What's in a price? How to price your products and services
michaelherold
243
12k
Designing Experiences People Love
moore
138
23k
What's new in Ruby 2.0
geeforr
343
31k
Practical Orchestrator
shlominoach
186
10k
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
329
21k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
232
17k
We Have a Design System, Now What?
morganepeng
50
7.2k
Docker and Python
trallard
40
3.1k
Bash Introduction
62gerente
608
210k
Agile that works and the tools we love
rasmusluckow
327
21k
Designing for Performance
lara
604
68k
Designing on Purpose - Digital PM Summit 2013
jponch
115
7k
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