Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Coroutines III : In-Depth Guide For Coroutines In Android

Coroutines III : In-Depth Guide For Coroutines In Android

These are the slides for the third session on coroutines. In this session I cover android specific coroutine scopes, available dispatchers and where they are used. And a code along of how it works.

Brian Odhiambo

July 03, 2023
Tweet

More Decks by Brian Odhiambo

Other Decks in Technology

Transcript

  1. 02 Design Centric Engineer Brian Odhiambo Dishwasher @ Baobab Circle

    Co-organizer @ KotlinKenya Maintaining @ KotlinBits Yeah am all about that UI/UX & Kotlin
  2. Scope Concurrency 03 viewmodels! lifecycle! dispatchers! Dispatchers Android specific dispatchers

    and where they are used Scopes Different android specific scopes and where to use each
  3. android devices have relatively small memory Little Memory all ui

    changes run on the main The UI & Main Thread Something to NOTE there has to be cooperation and collaboration Structured Concurrency
  4. UI or Non-Blocking code Dispatchers.Main Network and Disk operations Dispatchers.IO

    What dispatchers do we have available? CPU intensive tasks Dispatchers.Default inherits dispatcher that called it Dispatchers.Unconfined
  5. An Example Dispatchers import kotlinx.coroutines.* suspend fun main() { withContext(Dispatchers.Main)

    { ... } withContext(Dispatchers.Unconfined) { ... } withContext(Dispatchers.IO) { ... } withContext(Dispatchers.Default) { ... } } 06
  6. what is the job's lifecycle? who will cancel the job?

    who handles the exceptions thrown? Structured Concurrency
  7. tied to the lifecycle of the viewmodel viewModelScope tied to

    the lifecycle state of the component. Either activity or fragment lifecycleScope Different Out of The Box Scopes onCreate onStart onResume onPause onStop onDestroy
  8. An Example Coroutine context in purple import kotlinx.coroutines.* fun CoroutineScope.working(){

    println("I'm working in thread ${Thread.currentThread().name}") } fun main() = runBlocking<Unit> { launch { working() } launch(Dispatchers.Unconfined) { working() } launch(Dispatchers.Default) { working() } launch(CoroutineName("MyOwnThread")) { working() } } I'm working in thread main @coroutine#3 I'm working in thread DefaultDispatcher-worker-1 @coroutine#4 I'm working in thread main @coroutine#2 I'm working in thread main @MyOwnThread#5 09
  9. What is context switching? running a coroutine in a different

    thread Changing the context in which a coroutine runs Example import kotlinx.coroutines.* suspend fun main(){ doNetworkStuff() } suspend fun updateUi(){ withContext(Dispatchers.Main){ ... } } suspend fun doNetworkStuff(){ withContext(Dispatchers.IO){ ... updateUi() } }
  10. KotlinBits 😎 A fun and easy way to learn Kotlin

    in small bits and pieces. React, Comment & Share https://kotlinbits.vercel.app