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
Hack Claude Code with Claude Code
choplin
0
600
20250628_非エンジニアがバイブコーディングしてみた
ponponmikankan
0
670
iOS 26にアップデートすると実機でのHot Reloadができない?
umigishiaoi
0
120
コードの90%をAIが書く世界で何が待っているのか / What awaits us in a world where 90% of the code is written by AI
rkaga
50
33k
A2A プロトコルを試してみる
azukiazusa1
2
1.3k
AIと”コードの評価関数”を共有する / Share the "code evaluation function" with AI
euglena1215
1
150
今ならAmazon ECSのサービス間通信をどう選ぶか / Selection of ECS Interservice Communication 2025
tkikuc
21
3.9k
生成AI時代のコンポーネントライブラリの作り方
touyou
1
160
10 Costly Database Performance Mistakes (And How To Fix Them)
andyatkinson
0
220
Node-RED を(HTTP で)つなげる MCP サーバーを作ってみた
highu
0
120
“いい感じ“な定量評価を求めて - Four Keysとアウトカムの間の探求 -
nealle
1
8.8k
A full stack side project webapp all in Kotlin (KotlinConf 2025)
dankim
0
110
Featured
See All Featured
Building Applications with DynamoDB
mza
95
6.5k
How to train your dragon (web standard)
notwaldorf
94
6.1k
Facilitating Awesome Meetings
lara
54
6.4k
BBQ
matthewcrist
89
9.7k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
357
30k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
657
60k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
130
19k
Build your cross-platform service in a week with App Engine
jlugia
231
18k
Reflections from 52 weeks, 52 projects
jeffersonlam
351
20k
[RailsConf 2023] Rails as a piece of cake
palkan
55
5.6k
It's Worth the Effort
3n
185
28k
GraphQLの誤解/rethinking-graphql
sonatard
71
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