From the course: Intermediate Kotlin for Android Developers

Coroutines overview

From the course: Intermediate Kotlin for Android Developers

Start my 1-month free trial

Coroutines overview

- [Instructor] Kotin coroutines allow you to handle asynchronous tasks in your applications. This is very important on Android, as we need to avoid blocking the UI thread so we don't hinder the usability of our app. Right now, we tend to use callbacks to define what happens after a long running operation is complete. In this example, we're using a standard async task. We perform our potentially long running operation in the doInBackground method. And then in the onPostExecute method, we handle the results. But working with callbacks like this poses a few issues as our data needs become more complex. First, it can difficult to reason about. This is because we need to wrap our business logic inside of special methods, creating mere boiler plate code. Further, it's more challenging to chain calls together. If we have one request that depends on the results of another fort's execution, our code can get messy very quickly. It's for these reasons that the tech community has been moving toward other solutions like Future's reactive extensions and coroutines. Coroutines let you rewrite code in a linear style. This type of code is simple to reason about. In this example, we're launching a coroutine that will perform its operations on the UI thread. And then inside of it, we start another coroutine on a background thread. Finally, we just wait for the results before we continue with updating our UI. It's best to think of coroutines as being a state machine. You go from one state to the next. Each coroutine knowing about the one before it. This is what makes it simple to suspend computations and not block threads when working with coroutines. In fact, most people think of coroutines as lightweight threads. Now it's worth stating that coroutines are still in experimental status. But this does not mean that they are unstable. In fact, they're already being used in production by several applications. According to the Kotlin documentation, the design can be changed in a future release where there will be a migration path provided in the IDE. So there's no need to worry about using them.

Contents