Bringing work to the background with Coroutines in Android

Tram Ho

Introduce

Coroutines is no stranger to android developers anymore, but if we have used all the uses it brings in addition to using to call api with retrofit or to access db with room, sometimes we just understand it. features but do not know where to apply when Android dev. So let’s discuss in this article.

Perform

The concept of 60fps means that the system will redraw activity every time to reach 60 frames per second, meaning that each frame will be drawn in about 1/60 sec ~ 16 ms. App will need to perform the update logic on main threadsao for just under 16ms. If your app does too many things on the main thread, like just creating a view, calculating logic, the ability to each frame will take more than 16ms, then a drop frame phenomenon will occur. The longer the time per frame, the more easily recognized by the app lag, jerky. If your app has animation, the drop frame becomes more noticeable when the animation is not smooth.

And below is a typical log for frame drop

Skipped 55 frames! The application may be doing too much work on its main thread.

So what can we do? Try to put all the jobs that need much computation on the server, the computational logic in the app should be put in the background. Without coroutines, the manual thread management will be quite time consuming and error prone if not handled well, making up for us with great customization possibilities. Currently, coroutines are enough to handle such tasks, so we are not guilty of using it at all. If only talking about it, then it is like other theories, I would like to discuss more specifically for you to understand.

In MVVM model we processed data in ViewModel with viewModelScope , viewModelScope is suspend fun but by default it runs on Dispatchers.Main as shown below.

A better way is to move doWork to the background like this:

Note that if we want to update liveData to notify ui from within the background thread, we need to use livedata.post(value)

So, is coroutines good for Activity and Fragment? Has lifecycleScope suitable for handling UI socks

To show a tip after 5s, and after that 5s is hidden, the code already has callback hell, it’s not very good.

With coroutines it is much easier, note that the default lifecycleScope is also on Dispatchers.Main so don’t calculate any logic in this, or have withContext(Dispatchers.Default) and switch back to Dispatchers.Main when needing to update UI.

Refer

Kotlin Coroutines – Use Cases on Android https://github.com/LukasLechnerDev/Kotlin-Coroutine-Use-Cases-on-Android

Android Performance Patterns: Rendering Performance 101 https://www.youtube.com/watch?v=HXQhu6qfTVU

Share the news now

Source : Viblo