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
83
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
83
Getting Started With Kotlin
lpirro
0
64
Other Decks in Programming
See All in Programming
どうして僕の作ったクラスが手続き型と言われなきゃいけないんですか
akikogoto
1
120
Functional Event Sourcing using Sekiban
tomohisa
0
100
CSC509 Lecture 13
javiergs
PRO
0
110
Contemporary Test Cases
maaretp
0
140
受け取る人から提供する人になるということ
little_rubyist
0
250
OSSで起業してもうすぐ10年 / Open Source Conference 2024 Shimane
furukawayasuto
0
110
Compose 1.7のTextFieldはPOBox Plusで日本語変換できない
tomoya0x00
0
200
みんなでプロポーザルを書いてみた
yuriko1211
0
280
3 Effective Rules for Using Signals in Angular
manfredsteyer
PRO
1
100
subpath importsで始めるモック生活
10tera
0
320
TypeScript Graph でコードレビューの心理的障壁を乗り越える
ysk8hori
3
1.2k
型付き API リクエストを実現するいくつかの手法とその選択 / Typed API Request
euxn23
8
2.3k
Featured
See All Featured
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
47
5k
Building Your Own Lightsaber
phodgson
103
6.1k
StorybookのUI Testing Handbookを読んだ
zakiyama
27
5.3k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.3k
4 Signs Your Business is Dying
shpigford
180
21k
Navigating Team Friction
lara
183
14k
Being A Developer After 40
akosma
87
590k
Documentation Writing (for coders)
carmenintech
65
4.4k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
28
9.1k
We Have a Design System, Now What?
morganepeng
50
7.2k
"I'm Feeling Lucky" - Building Great Search Experiences for Today's Users (#IAC19)
danielanewman
226
22k
The Language of Interfaces
destraynor
154
24k
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