Share
Embed
Better Async With Kotlin Coroutines
Better Async With Kotlin Coroutines @ Kotlin Night Torino 2018
Leonardo Pirro
June 08, 2018
Transcript
40 slides
-
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 -
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 • 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 -
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() }§ -
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 } -
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