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
89
Getting Started With Kotlin
lpirro
0
65
Other Decks in Programming
See All in Programming
Python型ヒント完全ガイド 初心者でも分かる、現代的で実践的な使い方
mickey_kubo
1
140
ISUCON研修おかわり会 講義スライド
arfes0e2b3c
1
450
GitHub Copilot and GitHub Codespaces Hands-on
ymd65536
2
150
AI駆動のマルチエージェントによる業務フロー自動化の設計と実践
h_okkah
0
170
ruby.wasmで多人数リアルタイム通信ゲームを作ろう
lnit
3
490
システム成長を止めない!本番無停止テーブル移行の全貌
sakawe_ee
1
210
型で語るカタ
irof
0
200
状態遷移図を書こう / Sequence Chart vs State Diagram
orgachem
PRO
1
130
AI コーディングエージェントの時代へ:JetBrains が描く開発の未来
masaruhr
1
190
LT 2025-06-30: プロダクトエンジニアの役割
yamamotok
0
790
Startups on Rails in Past, Present and Future–Irina Nazarova, RailsConf 2025
irinanazarova
0
140
Node-RED を(HTTP で)つなげる MCP サーバーを作ってみた
highu
0
120
Featured
See All Featured
Fireside Chat
paigeccino
37
3.5k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
281
13k
Why Our Code Smells
bkeepers
PRO
336
57k
Being A Developer After 40
akosma
90
590k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
32
2.4k
Writing Fast Ruby
sferik
628
62k
Become a Pro
speakerdeck
PRO
29
5.4k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
251
21k
Gamification - CAS2011
davidbonilla
81
5.4k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
53
2.9k
Visualization
eitanlees
146
16k
Bash Introduction
62gerente
613
210k
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