Understand Kotlin Coroutines on Android (Google I/O'19)

Android Developers · 180K views · 2019 · 37:49

Open on YouTube

Software practice, open source & careersPython, Ruby & scripting languagesWeb developmenttalkdated

Why Stack Overflow recommends it

Stack Overflow users link it when answering or asking about lifecycleScope, viewModelScope, suspend functions and LiveData with coroutines, since it is the official walkthrough these APIs are explained from.

Recommended by 3 people across 2 different months, 2019 to 2021.

What it is

A Google I/O 2019 session by Android team members Sean McQuillan, Yigit Boyar and Sergey Vasilinetc on using Kotlin coroutines in Android apps. It covers turning callback code into sequential code, getting work off the main thread, integrating with Architecture Components (viewModelScope, lifecycleScope, LiveData), coroutine patterns, best practices and testing.

What people said

Recommends Kipr · 2019-07 · Stack Overflow · on “Suspend function 'callGetApi' should be called only from a coroutine or another suspend function”

Looks like the most elegant way to do it as of July 2019 , is the one described here [this video] : import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.launch class Activity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super... lifecycleScope.launch { val result = callGetApi() onResult(result) } } } Don't forget to add the correponding lib: implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha02"

Recommends Uruk Maat Ra · 2019-07 · Stack Overflow · on “How to get LiveData from Room?”

@MartinMarconcini I got idea from this "Understand Kotlin Coroutines on Android (Google I/O'19)" - They use LiveDate in Dao and then emitSource instead of emit [this video]

Recommends MrVasilev · 2019-09 · Stack Overflow · on “Using viewmodelScope launch with lifecycle transformations”

So, if I got everything correct maybe solution like this can help you: In you Activity/Fragment lifecycleScope.launchWhenStarted { val apiResult = viewModel.initView() updateUI(apiResult) } In your ViewModel private val apiDeferred = CompletableDeferred<LiveData<APIResult>>() suspend fun initView(): LiveData<APIResult> { viewModelScope.launch(Dispatchers.IO) { val apiResult = domain.performOperation() artsDeferred.complete(arts) } return apiDeferred.await() } And you can also check this video here: [this video] (after 22th min) Please, say if this works for you or no, I also can suggest another solutions with the newest tech coroutines, liveData and so on

Cites GuilhE · 2019-09 · Stack Overflow · on “viewModelScope not cancelled”

After watching Sean's explanation on Android (Google I/O'19) [this video] I've tried the same: init{ viewModelScope.launch { Timber.i("coroutine awake") while (true){ delay(2_000) Timber.i("another round trip") } } } Unfortunately onCleared it's called when the activity is killed but not when it's put in background ("when we move away from the Activity...", background is "moving away" imho ^^). And I get the following output: > ---- Activity in Foreground > 12:41:10.195 TEST: coroutine awake > 12:41:12.215 TEST: another round trip > 12:41:14.231 TEST: another round trip > 12:41:16.245 TEST: another round trip > 12:41:18.259 TEST: another round trip > 12:41:20.270 TEST: another round trip > -----

Cites Oya Canli · 2020-09 · Stack Overflow · on “How to access lifecycleScope of the host fragment from a custom view?”

I need to use coroutines inside a custom view. After watching this talk [this video] , I believe my best option is to use lifecycleScope as the coroutine scope, so that it will be automatically cancelled when lifecycleowner is destroyed. However I don't seem to have access to lifecycleScope inside the custom view. According to documentation [LINK] , we can either have access to it from a lifecycle object as lifecycle.coroutineScope or from a lifecycleOwner as lifecycleOwner.lifecycleScope . But custom view is not a lifecycle owner. So can I have access to lifecycleScope of the fragment somehow? Or if I can't, which coroutine context should I use instead?

Cites ngoson · 2020-09 · Stack Overflow · on “Problem with suspend function in Kotlin coroutine”

I am following this video to use Kotlin coroutine : [this video] , at 9:30 in the video. But when I write the similar code, it doesn't behave like i expected: WalletDao.kt interface WalletDao { @Query("SELECT * FROM wallet LIMIT 1") suspend fun getFirstWallet(): Wallet } Repository.kt class Repository private constructor(appContext: Context) { private val appDatabase = AppDatabase.getInstance(appContext) //current wallet private var _currentWallet : MutableLiveData<Wallet> = MutableLiveData() var currentWallet : LiveData<Wallet> = _currentWallet suspend fun initFirstWallet() { val fW = withContext(Dispatchers.IO) { appDatabase.walletDao.getFirstWallet() } _currentWallet.value = fW } } MainViewMod

Cites Miguel Lasa · 2021-07 · Stack Overflow · on “What does a suspend function mean in Kotlin coroutines?”

By this explanation it sounds like you could put anything inside `long running operation` and the thread will just pause the execution anywhere it sees fit. That doesn't sound accurate. Calling a blocking function from inside a suspend function will still block the thread it's running on. The suspend function will run, and if it finds another suspend function call, it will save its state, and free the thread for the next task in the call stack to be run. When that task is complete, the original function resumes. Anyway, that's just how I've understood it: [this video]