SlideShare a Scribd company logo
Improving app
performance with
Kotlin Coroutines
Hassan Abid - GDE Android 

Twitter / Instagram @hassanabidpk
What are coroutines?
–Android Developers Website
A coroutine is a concurrency design pattern that
you can use on Android to simplify code that
executes asynchronously.
–Kotlin documentation
Essentially, coroutines are light-weight threads.
Why we need coroutines?
Why we need Asynchronous
code?
Why we need coroutines?
Why we need Asynchronous?
• Main Thread has to update screen
every 16ms which is 60Hz (frames
per second)
fetchImage(url)
Callback vs. Sequential
// Async callbacks
networkRequest { result ->
   // Successful network request
   databaseSave(result) { rows ->
     // Result saved
   }
}
// The same code with coroutines
val result = networkRequest()
// Successful network request
databaseSave(result)
// Result saved
Why you should use
coroutines
RIP AsyncTaskRIP AsyncTask
AsyncTask
Coroutines
What problems do
coroutines solve?
• Manage long-running tasks

• Provides main-safety
Manage Long running Tasks
suspend fun fetchDocs() {                             // Dispatchers.Main
    val result = get("https://developer.android.com") // Dispatchers.IO for `get`
    show(result)                                      // Dispatchers.Main
}
suspend fun get(url: String) = withContext(Dispatchers.IO) { /* ... */ }
Main-safety
• Safely call network operations from main thread

• Safely call disk operations from main thread
Building blocks of
Coroutines
fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job
1
2
3
4
CoroutineContext
• Every coroutine in Kotlin has a context that is represented
by an instance of CoroutineContext interface

• Optimized : It stays on same dispatcher and avoids
switching threads
CoroutineDispatcher
• The coroutine context includes a coroutine
dispatcher that determines what thread or threads the
corresponding coroutine uses for its execution.
scope.launch(Dispatchers.Default) { // will get dispatched to
DefaultDispatcher
    // code
}
Dispatchers
suspend fun fetchDocs() {                      // Dispatchers.Main
    val result = get("developer.android.com")  // Dispatchers.Main
    show(result)                               // Dispatchers.Main
}
suspend fun get(url: String) =                 // Dispatchers.Main
    withContext(Dispatchers.IO) {              // Dispatchers.IO (main-safety block)
        /* perform network IO here */          // Dispatchers.IO (main-safety block)
    }                                          // Dispatchers.Main
}
Dispatchers
• Dispatchers.Main : Main Android Thread

• Dispatchers.IO : For Network and Database
(Room) calls

• Dispatchers.Default : For CPU-intensive tasks
CoroutineScope
• Defines a scope for new coroutines

• CoroutinesScope stops/cancels coroutines execution
when user leaves a content area with your app e.g
activity, fragment

• It should be implemented on entities with a well defined
lifecycle (activity, fragment)
What are suspend
functions?
Blocking Function
fun A()
fun B()
Suspending Function
fun A()
fun B()
suspended
Improving app performance with Kotlin Coroutines
Start a coroutine
Start a coroutine
• launch : Doesn’t return result to the caller

• async : Returns a result with suspend function
await
example : launch
returns a Job
without result
fun onDocsNeeded() {
    val job = viewModelScope.launch {    // Dispatchers.Main
        fetchDocs()            // Dispatchers.Main (suspend function call)
    }
job.cancel()
}
example : async
(Parallel Decomposition)
suspend fun fetchTwoDocs() =
    coroutineScope {
        val deferredOne = async { fetchDoc(1) }
        val deferredTwo = async { fetchDoc(2) }
        deferredOne.await()
        deferredTwo.await()
    }
returns a Deffered
CoroutineScope with Android
Arch Components
• Associate CoroutineScope implementations with a
lifecycle component

• Helps in avoiding Memory Leak

• Hint : ViewModel?
Coroutines with Android Arch
components
• viewModelScope

• use androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-beta01 or higher.
• lifeCycleScope

• use androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01 or higher.
• liveData 

• use androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01 or higher.
Life-cycle aware coroutines scope:
viewModelScope
class MyViewModel: ViewModel() {
    init {
        viewModelScope.launch {
            // Coroutine that will be canceled when the ViewModel is cleared.
        }
    }
}
Life-cycle aware coroutines scope:
lifeCycleScope
class MyFragment: Fragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewLifecycleOwner.lifecycleScope.launch {
            val params = TextViewCompat.getTextMetricsParams(textView)
            val precomputedText = withContext(Dispatchers.Default) {
                PrecomputedTextCompat.create(longTextContent, params)
            }
            TextViewCompat.setPrecomputedText(textView, precomputedText)
        }
    }
}
Special cases
Special cases
class MyFragment: Fragment {
    init {
        lifecycleScope.launchWhenStarted {
            try {
                // Call some suspend functions.
            } finally {
                // This line might execute after Lifecycle is DESTROYED.
                if (lifecycle.state >= STARTED) {
                    // Here, since we've checked, it is safe to run any
                    // Fragment transactions.
                }
            }
        }
    }
}
Life-cycle aware coroutines scope:
liveData
val user: LiveData<Result> = liveData {
    emit(Result.loading())
    try {
        emit(Result.success(fetchUser()))
    } catch(ioException: Exception) {
        emit(Result.error(ioException))
    }
}
fun <T> liveData(
context: CoroutineContext =
EmptyCoroutineContext,..)
Demo




https://github.com/
hassanabidpk/searchrestaurant/

https://github.com/
hassanabidpk/PizzaFinder
Improving app performance with Kotlin Coroutines
There is more…..
Flow
• Flow is a cold stream that give us same behaviour as that
of Observable and Flowable in RxJava

• Android Dev Summit 2019 Talk https://
www.youtube.com/watch?v=B8ppnjGPAGE

• Docs : https://kotlinlang.org/docs/reference/coroutines/
flow.html
Coroutines for Reactive Streams
kotlinx-coroutines-reactive -- utilities for Reactive Streams
kotlinx-coroutines-reactor -- utilities for Reactor
kotlinx-coroutines-rx2 -- utilities for RxJava 2.x
Summary
• Coroutines are great - Start using them

• If you are already using RxJava, you are FINE. You can
slowly migrate to Coroutines.
Resources (Videos)
• Android Suspenders (Android Dev Summit 2019) https://
www.youtube.com/watch?v=EOjq4OIWKqM

• Understanding Coroutines on Android (Google IO 19)
https://www.youtube.com/watch?v=BOHK_w09pVA
Resources (Docs)
• Kotlin Docs : https://kotlinlang.org/docs/reference/
coroutines-overview.html

• Android + Coroutines Docs : https://
developer.android.com/kotlin/coroutine

• Coroutines + Android Arch components : https://
developer.android.com/topic/libraries/architecture/
coroutines
Thank You

More Related Content

PDF
Introduction to kotlin coroutines
PDF
Kotlin Coroutines and Android sitting in a tree
PPTX
Android kotlin coroutines
PDF
Introduction to Kotlin coroutines
PPTX
Coroutines in Kotlin
PDF
Kotlin Coroutines. Flow is coming
PDF
Nextcloud manual
PDF
Google Kubernetes Engine (GKE) deep dive
Introduction to kotlin coroutines
Kotlin Coroutines and Android sitting in a tree
Android kotlin coroutines
Introduction to Kotlin coroutines
Coroutines in Kotlin
Kotlin Coroutines. Flow is coming
Nextcloud manual
Google Kubernetes Engine (GKE) deep dive

What's hot (20)

PPTX
UI Programming with Qt-Quick and QML
PPTX
Kotlin presentation
PPTX
Basics of Java Concurrency
KEY
JavaOne 2012 - JVM JIT for Dummies
PPT
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
PDF
Data Persistence in Android with Room Library
PDF
Introduction to Coroutines @ KotlinConf 2017
PPTX
Golang - Overview of Go (golang) Language
PPT
JUnit 4
PDF
Graal and Truffle: One VM to Rule Them All
PDF
Test unitaires
PDF
Kotlin Coroutines - the new async
PPTX
CI-CD WITH GITLAB WORKFLOW
PDF
Coroutines for Kotlin Multiplatform in Practise
PDF
Introduction to Docker
PPTX
Introduction to Apache Camel
PDF
Kotlin for Android Development
PDF
Deep dive into Coroutines on JVM @ KotlinConf 2017
PDF
PPTX
What Are Coroutines In Kotlin?
UI Programming with Qt-Quick and QML
Kotlin presentation
Basics of Java Concurrency
JavaOne 2012 - JVM JIT for Dummies
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
Data Persistence in Android with Room Library
Introduction to Coroutines @ KotlinConf 2017
Golang - Overview of Go (golang) Language
JUnit 4
Graal and Truffle: One VM to Rule Them All
Test unitaires
Kotlin Coroutines - the new async
CI-CD WITH GITLAB WORKFLOW
Coroutines for Kotlin Multiplatform in Practise
Introduction to Docker
Introduction to Apache Camel
Kotlin for Android Development
Deep dive into Coroutines on JVM @ KotlinConf 2017
What Are Coroutines In Kotlin?
Ad

Similar to Improving app performance with Kotlin Coroutines (20)

PDF
Quick Introduction to Kotlin Coroutine for Android Dev
PDF
Kotlin coroutine - the next step for RxJava developer?
PDF
droidcon Transylvania - Kotlin Coroutines
PPTX
Coroutines talk ppt
PDF
Coroutines
PDF
Should it be routine to use coroutines?
PDF
Managing parallelism using coroutines
PDF
Aplicações assíncronas no Android com
Coroutines & Jetpack
PDF
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
PPTX
Exploring Kotlin
PDF
Kotlin from-scratch 3 - coroutines
PDF
Structured concurrency with Kotlin Coroutines
PDF
Aplicações Assíncronas no Android com Coroutines e Jetpack
PDF
Kotlin - Coroutine
PDF
Lean way write asynchronous code with Kotlin’s coroutines - Ronen Sabag, Gett
PDF
Aplicações assíncronas no Android com
Coroutines & Jetpack
PDF
Aplicações assíncronas no Android com Coroutines & Jetpack
PDF
Kotlin Coroutines in Practice @ KotlinConf 2018
PDF
DroidConEgypt-21-10-2022-Coroutines-AhmedNabil.pdf
PPTX
2019-01-29 - Demystifying Kotlin Coroutines
Quick Introduction to Kotlin Coroutine for Android Dev
Kotlin coroutine - the next step for RxJava developer?
droidcon Transylvania - Kotlin Coroutines
Coroutines talk ppt
Coroutines
Should it be routine to use coroutines?
Managing parallelism using coroutines
Aplicações assíncronas no Android com
Coroutines & Jetpack
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Exploring Kotlin
Kotlin from-scratch 3 - coroutines
Structured concurrency with Kotlin Coroutines
Aplicações Assíncronas no Android com Coroutines e Jetpack
Kotlin - Coroutine
Lean way write asynchronous code with Kotlin’s coroutines - Ronen Sabag, Gett
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com Coroutines & Jetpack
Kotlin Coroutines in Practice @ KotlinConf 2018
DroidConEgypt-21-10-2022-Coroutines-AhmedNabil.pdf
2019-01-29 - Demystifying Kotlin Coroutines
Ad

More from Hassan Abid (18)

PDF
[IO Extended KL] On-Device AI: Is It Time to Go All-In, or Do We Still Need t...
PDF
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
PDF
DevFest SG 2024 - What’s new in On-device Generative AI
PDF
What’s new in Android: Embracing era of Generative AI
PDF
Android 101 - Kotlin ( Future of Android Development)
PDF
Exploring CameraX from JetPack
PDF
What’s new in Android JetPack
PDF
Kotlin for Android Developers
PDF
Building Modern Apps using Android Architecture Components
PDF
Recap of Android Dev Summit 2018
PDF
What's new in Android Pie
PDF
Android Jetpack - Google IO Extended Singapore 2018
PDF
Django for mobile applications
PDF
VR Video Apps on Daydream
PDF
Best Practices in Media Playback
PDF
ExoPlayer for Application developers
PPTX
Android n preview
PDF
Introduction to Pakistan
[IO Extended KL] On-Device AI: Is It Time to Go All-In, or Do We Still Need t...
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
DevFest SG 2024 - What’s new in On-device Generative AI
What’s new in Android: Embracing era of Generative AI
Android 101 - Kotlin ( Future of Android Development)
Exploring CameraX from JetPack
What’s new in Android JetPack
Kotlin for Android Developers
Building Modern Apps using Android Architecture Components
Recap of Android Dev Summit 2018
What's new in Android Pie
Android Jetpack - Google IO Extended Singapore 2018
Django for mobile applications
VR Video Apps on Daydream
Best Practices in Media Playback
ExoPlayer for Application developers
Android n preview
Introduction to Pakistan

Recently uploaded (20)

PPTX
CHAPTER 2 - PM Management and IT Context
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
history of c programming in notes for students .pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Cost to Outsource Software Development in 2025
PPTX
Transform Your Business with a Software ERP System
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
System and Network Administration Chapter 2
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
L1 - Introduction to python Backend.pptx
PDF
top salesforce developer skills in 2025.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
assetexplorer- product-overview - presentation
CHAPTER 2 - PM Management and IT Context
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Navsoft: AI-Powered Business Solutions & Custom Software Development
Why Generative AI is the Future of Content, Code & Creativity?
Design an Analysis of Algorithms I-SECS-1021-03
history of c programming in notes for students .pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Cost to Outsource Software Development in 2025
Transform Your Business with a Software ERP System
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Wondershare Filmora 15 Crack With Activation Key [2025
System and Network Administration Chapter 2
PTS Company Brochure 2025 (1).pdf.......
L1 - Introduction to python Backend.pptx
top salesforce developer skills in 2025.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
assetexplorer- product-overview - presentation

Improving app performance with Kotlin Coroutines

  • 1. Improving app performance with Kotlin Coroutines Hassan Abid - GDE Android 
 Twitter / Instagram @hassanabidpk
  • 3. –Android Developers Website A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously.
  • 5. Why we need coroutines? Why we need Asynchronous code? Why we need coroutines?
  • 6. Why we need Asynchronous? • Main Thread has to update screen every 16ms which is 60Hz (frames per second) fetchImage(url)
  • 8. // Async callbacks networkRequest { result ->    // Successful network request    databaseSave(result) { rows ->      // Result saved    } } // The same code with coroutines val result = networkRequest() // Successful network request databaseSave(result) // Result saved
  • 9. Why you should use coroutines
  • 12. What problems do coroutines solve? • Manage long-running tasks • Provides main-safety
  • 13. Manage Long running Tasks suspend fun fetchDocs() {                             // Dispatchers.Main     val result = get("https://developer.android.com") // Dispatchers.IO for `get`     show(result)                                      // Dispatchers.Main } suspend fun get(url: String) = withContext(Dispatchers.IO) { /* ... */ }
  • 14. Main-safety • Safely call network operations from main thread • Safely call disk operations from main thread
  • 16. fun CoroutineScope.launch(     context: CoroutineContext = EmptyCoroutineContext,     start: CoroutineStart = CoroutineStart.DEFAULT,     block: suspend CoroutineScope.() -> Unit ): Job 1 2 3 4
  • 17. CoroutineContext • Every coroutine in Kotlin has a context that is represented by an instance of CoroutineContext interface • Optimized : It stays on same dispatcher and avoids switching threads
  • 18. CoroutineDispatcher • The coroutine context includes a coroutine dispatcher that determines what thread or threads the corresponding coroutine uses for its execution. scope.launch(Dispatchers.Default) { // will get dispatched to DefaultDispatcher     // code }
  • 19. Dispatchers suspend fun fetchDocs() {                      // Dispatchers.Main     val result = get("developer.android.com")  // Dispatchers.Main     show(result)                               // Dispatchers.Main } suspend fun get(url: String) =                 // Dispatchers.Main     withContext(Dispatchers.IO) {              // Dispatchers.IO (main-safety block)         /* perform network IO here */          // Dispatchers.IO (main-safety block)     }                                          // Dispatchers.Main }
  • 20. Dispatchers • Dispatchers.Main : Main Android Thread • Dispatchers.IO : For Network and Database (Room) calls • Dispatchers.Default : For CPU-intensive tasks
  • 21. CoroutineScope • Defines a scope for new coroutines • CoroutinesScope stops/cancels coroutines execution when user leaves a content area with your app e.g activity, fragment • It should be implemented on entities with a well defined lifecycle (activity, fragment)
  • 27. Start a coroutine • launch : Doesn’t return result to the caller • async : Returns a result with suspend function await
  • 28. example : launch returns a Job without result fun onDocsNeeded() {     val job = viewModelScope.launch {    // Dispatchers.Main         fetchDocs()            // Dispatchers.Main (suspend function call)     } job.cancel() }
  • 29. example : async (Parallel Decomposition) suspend fun fetchTwoDocs() =     coroutineScope {         val deferredOne = async { fetchDoc(1) }         val deferredTwo = async { fetchDoc(2) }         deferredOne.await()         deferredTwo.await()     } returns a Deffered
  • 30. CoroutineScope with Android Arch Components • Associate CoroutineScope implementations with a lifecycle component • Helps in avoiding Memory Leak • Hint : ViewModel?
  • 31. Coroutines with Android Arch components • viewModelScope • use androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-beta01 or higher. • lifeCycleScope • use androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01 or higher. • liveData • use androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01 or higher.
  • 32. Life-cycle aware coroutines scope: viewModelScope class MyViewModel: ViewModel() {     init {         viewModelScope.launch {             // Coroutine that will be canceled when the ViewModel is cleared.         }     } }
  • 33. Life-cycle aware coroutines scope: lifeCycleScope class MyFragment: Fragment() {     override fun onViewCreated(view: View, savedInstanceState: Bundle?) {         super.onViewCreated(view, savedInstanceState)         viewLifecycleOwner.lifecycleScope.launch {             val params = TextViewCompat.getTextMetricsParams(textView)             val precomputedText = withContext(Dispatchers.Default) {                 PrecomputedTextCompat.create(longTextContent, params)             }             TextViewCompat.setPrecomputedText(textView, precomputedText)         }     } }
  • 35. Special cases class MyFragment: Fragment {     init {         lifecycleScope.launchWhenStarted {             try {                 // Call some suspend functions.             } finally {                 // This line might execute after Lifecycle is DESTROYED.                 if (lifecycle.state >= STARTED) {                     // Here, since we've checked, it is safe to run any                     // Fragment transactions.                 }             }         }     } }
  • 36. Life-cycle aware coroutines scope: liveData val user: LiveData<Result> = liveData {     emit(Result.loading())     try {         emit(Result.success(fetchUser()))     } catch(ioException: Exception) {         emit(Result.error(ioException))     } } fun <T> liveData( context: CoroutineContext = EmptyCoroutineContext,..)
  • 37. Demo
  • 41. Flow • Flow is a cold stream that give us same behaviour as that of Observable and Flowable in RxJava • Android Dev Summit 2019 Talk https:// www.youtube.com/watch?v=B8ppnjGPAGE • Docs : https://kotlinlang.org/docs/reference/coroutines/ flow.html
  • 42. Coroutines for Reactive Streams kotlinx-coroutines-reactive -- utilities for Reactive Streams kotlinx-coroutines-reactor -- utilities for Reactor kotlinx-coroutines-rx2 -- utilities for RxJava 2.x
  • 43. Summary • Coroutines are great - Start using them • If you are already using RxJava, you are FINE. You can slowly migrate to Coroutines.
  • 44. Resources (Videos) • Android Suspenders (Android Dev Summit 2019) https:// www.youtube.com/watch?v=EOjq4OIWKqM • Understanding Coroutines on Android (Google IO 19) https://www.youtube.com/watch?v=BOHK_w09pVA
  • 45. Resources (Docs) • Kotlin Docs : https://kotlinlang.org/docs/reference/ coroutines-overview.html • Android + Coroutines Docs : https:// developer.android.com/kotlin/coroutine • Coroutines + Android Arch components : https:// developer.android.com/topic/libraries/architecture/ coroutines