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
はやい・やすい・うまい!スタートアップでも使える Retrofit + RxJava で瞬間A...
Search
Fumihiko Shiroyama
July 14, 2017
Technology
2
590
はやい・やすい・うまい!スタートアップでも使える Retrofit + RxJava で瞬間APIクッキングレシピ
はやい・やすい・うまい!スタートアップでも使える Retrofit + RxJava で瞬間APIクッキングレシピ
Fumihiko Shiroyama
July 14, 2017
Tweet
Share
More Decks by Fumihiko Shiroyama
See All by Fumihiko Shiroyama
The world of Android wireless communications without Internet
srym
1
120
AWS Device FarmとCircleCIでAndroidのUIテストを自動化しよう
srym
1
4.9k
Spring BootをKotlinで作成しAmazon Elastic Container Service (ECS) で稼働させる
srym
6
1.9k
iOSDC_2019_DeviceFarm.pdf
srym
8
19k
世界で戦うエンジニアになるために_公開用.pdf
srym
18
45k
Unit Testing in a Nutshell - DroidKaigi 2018
srym
11
15k
Clean Architecture & TDD
srym
1
3.7k
I/O 2017 Short Report
srym
0
300
Mock Partially using Dagger
srym
0
650
Other Decks in Technology
See All in Technology
OCI Network Firewall 概要
oracle4engineer
PRO
0
4.1k
20241120_JAWS_東京_ランチタイムLT#17_AWS認定全冠の先へ
tsumita
2
240
マルチモーダル / AI Agent / LLMOps 3つの技術トレンドで理解するLLMの今後の展望
hirosatogamo
37
12k
ExaDB-D dbaascli で出来ること
oracle4engineer
PRO
0
3.8k
TypeScriptの次なる大進化なるか!? 条件型を返り値とする関数の型推論
uhyo
2
1.6k
Amazon Personalizeのレコメンドシステム構築、実際何するの?〜大体10分で具体的なイメージをつかむ〜
kniino
1
100
The Role of Developer Relations in AI Product Success.
giftojabu1
0
120
元旅行会社の情シス部員が教えるおすすめなre:Inventへの行き方 / What is the most efficient way to re:Invent
naospon
2
330
RubyのWebアプリケーションを50倍速くする方法 / How to Make a Ruby Web Application 50 Times Faster
hogelog
3
940
サイバーセキュリティと認知バイアス:対策の隙を埋める心理学的アプローチ
shumei_ito
0
380
AGIについてChatGPTに聞いてみた
blueb
0
130
Lambdaと地方とコミュニティ
miu_crescent
2
370
Featured
See All Featured
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
131
33k
YesSQL, Process and Tooling at Scale
rocio
169
14k
Agile that works and the tools we love
rasmusluckow
327
21k
Put a Button on it: Removing Barriers to Going Fast.
kastner
59
3.5k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.3k
Making the Leap to Tech Lead
cromwellryan
133
8.9k
Building Your Own Lightsaber
phodgson
103
6.1k
Making Projects Easy
brettharned
115
5.9k
Designing Dashboards & Data Visualisations in Web Apps
destraynor
229
52k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
44
6.8k
Automating Front-end Workflow
addyosmani
1366
200k
Unsuck your backbone
ammeep
668
57k
Transcript
͍ɾ͍͢ɾ͏·͍ʂ ελʔτΞοϓͰ͑Δ Retrofit + RxJava ͰॠؒAPIΫο ΩϯάϨγϐ @fushiroyama
About Me • Fumihiko Shiroyama • Android App Developer •
https://github.com/srym
How to implement REST Client? • HTTP Client • Thread
Executer • JSON Deserializer • Integration with RxJava
Retrofit
Retrofit • A type-safe HTTP client for Android and Java
• http://square.github.io/retrofit/ • by Square
Install // Retrofit compile "com.squareup.retrofit2:retrofit:${retrofitVersion}" compile "com.squareup.retrofit2:adapter-rxjava2:${retrofitVersion}" compile "com.squareup.retrofit2:converter-gson:${retrofitVersion}" //
RxJava compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile "io.reactivex.rxjava2:rxjava:2.1.1"
Retrofit public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user);
}
Retrofit Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build(); GitHubService service
= retrofit.create(GitHubService.class);
Retrofit GitHubService service = retrofit.create(GitHubService.class); Call<List<Repo>> repos = service.listRepos("srym"); //
synchronous call Response<List<Repo>> response = repos.execute(); // asynchronous call repos.enqueue( /* callback here */ );
Integration with RxJava Retrofit retrofit = new Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl("https://api.github.com/") .build();
Change Return Type public interface GitHubService { @GET("users/{user}/repos") Single<List<Repo>> listRepos(@Path("user")
String user); }
Subscribe Single<List<Repo>> repos = service.listRepos("srym") repos .subscribe( list -> doSomethingToList(list),
throwable -> Timber.d(throwable.getMessage(), throwable), () -> Timber.d("complete") );
Link • RxJava+RetrofitͰAPI௨৴पΓΛ࣮͢Δ͏͑ Ͱ࠷ݶͷࣝΛ30Ͱ٧ΊࠐΉ • http://qiita.com/FumihikoSHIROYAMA/ items/201536d9b45ef21b6bc7
Link • RetrofitΛͬͨOAuth࠶ೝূΞϓϩʔν • http://qiita.com/FumihikoSHIROYAMA/ items/ac1beaeaa9b4baaed939
Link • RetrofitΛͬͨAPIݺͼग़͠ͰϦΧόϦՄೳ ͳHTTPΤϥʔΛͲ͏ѻ͏͔ • http://qiita.com/FumihikoSHIROYAMA/ items/65d52aea1a9f324d347e
What's Good about Retrofit + Rx • Easy to define
• Easy to compose • Easy to test
Test • MockWebServer • TestSubscriber
MockWebServer • A scriptable web server for testing HTTP clients
• https://github.com/square/okhttp/tree/ master/mockwebserver
MockWebServer private final MockWebServer mockWebServer = new MockWebServer();
MockWebServer Dispatcher dispatcher = new Dispatcher() { @Override public MockResponse
dispatch(RecordedRequest request) throws InterruptedException { return new MockResponse().setResponseCode(404); } }; mockWebServer.setDispatcher(dispatcher); mockWebServer.start();
MockWebServer @Override public MockResponse dispatch(RecordedRequest request) { if (request ==
null || request.getPath() == null) { return new MockResponse().setResponseCode(400); } if (request.getPath().matches("/users/.+/repos")) { return new MockResponse().setBody( readJsonFromResources("users_repos.json") ).setResponseCode(200); } return new MockResponse().setResponseCode(404); }
MockWebServer Retrofit retrofit = new Retrofit.Builder() .baseUrl(mockWebServer.url("")) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build();
GitHubService gitHubService = retrofit.create(GitHubService.class);
TestSubscriber • A TestSubscriber is a variety of Subscriber that
you can use for unit testing, to perform assertions, inspect received events, or wrap a mocked Subscriber. • http://reactivex.io/RxJava/javadoc/rx/ observers/TestSubscriber.html
TestSubscriber restGitHubDataSource .listRepos("srym") .test();
TestSubscriber List<Repo> repos = restGitHubDataSource.listRepos("srym") .test() .await() .assertNoErrors() .assertComplete() .values()
.get(0); assertThat(repos).isNotNull();
TestSubscriber • https://github.com/srym/Architecture • https://github.com/srym/Architecture/blob/ master/app/src/test/java/us/shiroyama/ android/architecture/infrastructure/ repository/datasource/remote/ RestGitHubDataSourceTest.java
Easy to compose • Rx's Observable is easily & flexibly
combined • Avoid callback hells
Easy to compose public class GitHubInfraRepository implements GitHubRepository { private
final RemoteGitHubDataSource remoteDataSource; private final RepoMapper mapper; @Inject public GitHubInfraRepository(RemoteGitHubDataSource remoteDataSource, RepoMapper mapper) { this.remoteDataSource = remoteDataSource; this.mapper = mapper; } @Override public Single<List<RepoModel>> listRepos(@NonNull String user) { return remoteDataSource .listRepos(user) .map(mapper::convert); } }
Easy to compose private final RemoteGitHubDataSource remoteDataSource; private final LocalGitHubDataSource
localGitHubDataSource; private final RepoMapper mapper; @Inject public GitHubInfraRepository(RemoteGitHubDataSource remoteDataSource, LocalGitHubDataSource localGitHubDataSource, RepoMapper mapper) { this.remoteDataSource = remoteDataSource; this.localGitHubDataSource = localGitHubDataSource; this.mapper = mapper; }
Easy to compose @Override public Single<List<RepoModel>> listRepos(@NonNull String user) {
return remoteDataSource .listRepos(user) .map(mapper::convert);
Easy to compose public Single<List<RepoModel>> listRepos(@NonNull String user) { return
localGitHubDataSource .listRepos(user) .onErrorResumeNext( remoteDataSource .listRepos(user) .retry(DEFAULT_RETRY) .doOnSuccess(localGitHubDataSource::save) ) .map(mapper::convert);
Android Clean Architecture • android10/Android-CleanArchitecture • https://github.com/android10/Android- CleanArchitecture • srym/Architecture
• https://github.com/srym/Architecture
None