Android Kotlin Coroutines

Old Way of Threading

This way of creating threads in Android is actually a hassle. What if you want to update the UI at different times? It’s going to look something like this:

Attack of the uiThreads! Theirs already two uiThreads taking up a lot of lines in our code! Every time we want to update the UI we need to open up with uiThread.

Coroutines to the Rescue!

Let’s get started with Coroutines and improve our code readability!

Dependencies

Getting Dirty

You aren’t going to be using async{ } anymore. Instead, you’re using async(UI){ }. They look very similar, instead of async(UI) being in the background thread, it starts in the UI thread.

You might be thinking, “What’s the point of starting an async task if it’s on the UI thread?” I hear ya Jim, and the answer is because whenever you do an async task, we usually update the UI thread right after.You can actually go in the background thread with a function called bg{ }. I’ll show you here:

What’s that await() do? That the benefit of coroutines. You can delay your asynchronous tasks. When using the bg{ } the code in there isn’t run yet. It’s run when text.await() is run. So we can do things like this:

You can now time your asynchronous tasks. There is no going in and out of the UI thread. Having the ability to delay your async tasks is powerful and can make your code easier to look at!

Leave a Reply

Your email address will not be published. Required fields are marked *