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
Better Async With Kotlin Coroutines
Search
Leonardo Pirro
June 08, 2018
Programming
1
89
Better Async With Kotlin Coroutines
Better Async With Kotlin Coroutines @ Kotlin Night Torino 2018
Leonardo Pirro
June 08, 2018
Tweet
Share
More Decks by Leonardo Pirro
See All by Leonardo Pirro
Android JetPack: easy navigation with the new Navigation Controller
lpirro
2
190
Empower your app with MVP & Architecture Components
lpirro
0
90
Getting Started With Kotlin
lpirro
0
65
Other Decks in Programming
See All in Programming
Understanding Ruby Grammar Through Conflicts
yui_knk
1
120
AI OCR API on Lambdaを Datadogで可視化してみた
nealle
0
170
Claude Codeで実装以外の開発フロー、どこまで自動化できるか?失敗と成功
ndadayo
2
770
バイブコーディングの正体——AIエージェントはソフトウェア開発を変えるか?
stakaya
5
1k
Constant integer division faster than compiler-generated code
herumi
2
690
TDD 実践ミニトーク
contour_gara
0
130
CEDEC 2025 『ゲームにおけるリアルタイム通信への QUIC導入事例の紹介』
segadevtech
3
960
Portapad紹介プレゼンテーション
gotoumakakeru
1
130
書き捨てではなく継続開発可能なコードをAIコーディングエージェントで書くために意識していること
shuyakinjo
1
300
一人でAIプロダクトを作るための工夫 〜技術選定・開発プロセス編〜 / I want AI to work harder
rkaga
12
2.8k
Kiroの仕様駆動開発から見えてきたAIコーディングとの正しい付き合い方
clshinji
1
130
エンジニアのための”最低限いい感じ”デザイン入門
shunshobon
0
130
Featured
See All Featured
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
26k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
183
54k
Agile that works and the tools we love
rasmusluckow
329
21k
GraphQLとの向き合い方2022年版
quramy
49
14k
For a Future-Friendly Web
brad_frost
179
9.9k
Product Roadmaps are Hard
iamctodd
PRO
54
11k
Mobile First: as difficult as doing things right
swwweet
223
9.9k
StorybookのUI Testing Handbookを読んだ
zakiyama
30
6k
Building Better People: How to give real-time feedback that sticks.
wjessup
367
19k
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
161
15k
Scaling GitHub
holman
462
140k
The World Runs on Bad Software
bkeepers
PRO
70
11k
Transcript
Better Async with context() Kotlin Coroutines Leonardo Pirro Android Developer
@ IQUII @lpirro93
Who Am I? Hi, I’m Leo. Android Developer @ IQUII
Why Coroutines? Coroutines simplify asynchronous programming by providing a set
of APIs to write code in direct style (sequentially)
Why Coroutines? • Asynchronous programming is becoming really important for
developers • The other tools that we have today introduced a lot of complexity • Callback Hell
None
What we have now Thread { code } .start() object
MyAsyncTask: AsyncTask() { override fun doInBackground { code } override fun onPostExcecute { code } } Observable.just(1,2,3,4) .map { code } .doOnEach { code } .doOnError { code } .subscribeOn( { onNext }, { onError } )
What we have now Thread { code } .start() object
MyAsyncTask: AsyncTask() { override fun doInBackground { code } override fun onPostExcecute { code } } Observable.just(1,2,3,4) .map { code } .doOnEach { code } .doOnError { code } .subscribeOn( { onNext }, { onError } )
What we have now WANT fun loadNews() = launch {
view.showLoading() val result = async { // computation }.await() view.hideLoading() view.showData(result) }
Coroutines
Coroutines • Introduced in Kotlin 1.1 • Experimental (but several
companies, including us in IQUII, are using them in production with zero problems)
coroutine builder coroutine context suspend function builders to launch coroutine
coroutine dispatchers mark suspention point Coroutines
coroutine builder builders to launch coroutine coroutine context suspend function
coroutine dispatchers mark suspention point Coroutines
coroutine builder coroutine context suspend function builders to launch coroutine
coroutine dispatchers mark suspention point Coroutines
coroutine builder coroutine context suspend function builders to launch coroutine
coroutine dispatchers mark suspention point Coroutines
Coroutines - Builders withContext return result uncaught exception crashes your
app T launch Job fire and forget uncaught exception crashes your app async Deferred returns non-blocking future uncaught exception is shared inside the resulting Deferred
Coroutines - Context coroutine context UI dispatch execution into Android
main thread CommonPool dispatch execution into background thread Unconfined dispatch execution into current thread
Coroutines - Suspend Function suspend fun fetchNews(): News suspend function
fun fetchNews(listener: Continuation<News>) Trasformed to
None
How to create a coroutine
How to create a coroutine fun loadPlayes() { view?.showLoading() val
result = dataManager.getPlayers() view?.showPlayers(result) view?.hideLoading() }§
How to create a coroutine fun loadPlayes() = launch( §
UI § ) { view?.showLoading() val result = dataManager.getPlayers() view?.showPlayers(result) view?.hideLoading() }§
How to create a coroutine Parent coroutine fun loadPlayes() =
launch( § UI § ) { § view?.showLoading() val result = dataManager.getPlayers() view?.showPlayers(result) view?.hideLoading() }§
How to create a coroutine Result in UI Thread fun
loadPlayes() = launch(UI) { § view?.showLoading() val result = dataManager.getPlayers() view?.showPlayers(result) view?.hideLoading() }§
How to create a coroutine fun loadPlayes() = launch(UI) {
view?.showLoading() val result = dataManager.getPlayers() view?.showPlayers(result) view?.hideLoading() }§
How to create a coroutine fun loadPlayes() = launch(UI) {
view?.showLoading() val result = withContext(CommonPool) { dataManager.getPlayers() } view?.showPlayers(result) view?.hideLoading() }§
How to create a coroutine fun loadPlayes() = launch(UI) {
view?.showLoading() val result = withContext(CommonPool) { dataManager.getPlayers() } view?.showPlayers(result) view?.hideLoading() }§ child coroutine
How to create a coroutine fun loadPlayes() = launch(UI) {
view?.showLoading() val result = withContext(CommonPool) { dataManager.getPlayers() } view?.showPlayers(result) view?.hideLoading() }§
What about cancellation?
Cancelling a coroutine var job: Job? = null fun onPlayerButtonClicked(){
job = loadPlayers() } fun onBackClicked(){ job?.cancel() } private fun loadPlayers() = launch(UI) { // code }
Cancelling a coroutine var job: Job? = null fun onPlayerButtonClicked(){
job = loadPlayers() } fun onBackClicked(){ job?.cancel() } private fun loadPlayers() = launch(UI) { // code }
Cancelling a coroutine var job: Job? = null fun onPlayerButtonClicked(){
job = loadPlayers() } fun onBackClicked(){ job?.cancel() } private fun loadPlayers() = launch(UI) { // code }
What about error handling? try { } catch(err: SlideNotFoundException) {
}
Error handling - try/catch block fun loadPlayes() = launch(UI) {
view?.showLoading() try { val result = withContext(CommonPool) { dataManager.getPlayers() view?.showPlayers(result) } catch (e: IllegalArgumentException) { // handle errors } view?.hideLoading() }
Error handling - Store inside Deferred fun loadPlayes() = async(UI)
{ view?.showLoading() val task = async(CommonPool) { dataManager.getPlayers() } val result = task.await() view?.showPlayers(result) view?.hideLoading() }
Error handling - Store inside Deferred var job: Deferred<*> =
loadPlayes() job.invokeOnCompletion { it?.printStackTrace() }
Other cool stuff - Retrofit 2 Adapter interface MyApiService {
@GET("user") fun getuser(): Deferred<User> // or... @GET("user") fun getuser(): Deferred<Response<User>> }
Setup Coroutines implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.2" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:0.22.2" build.gradle kotlin { experimental
{ coroutines 'enable' } } gradle.properties kotlin.coroutines=enable
Link utili • Kotlin community: https://kotlinlang.org/community • Official Slack: http://slack.kotlinlang.org
• Android Developers Italy: https://androiddevsitaly.slack.com • Kotlin Coroutines official guide: https://github.com/Kotlin/ kotlinx.coroutines/blob/master/coroutines-guide.md Slide of this talk: https://speakerdeck.com/lpirro
http://www.androiddevs.it Slack community - Android Developers Italia
Thank You Leonardo Pirro Android Developer @ IQUII @lpirro93