Coroutine in Android : What is Coroutine ?

Hello All,

This post is for anyone interested in learning more about Kotlin Coroutines but isn't sure what they are. The purpose is to help you grasp what Kotlin Coroutines are, hence there have been some simplifications made.

What is Coroutine ?

  • Our application runs on the main thread, which handles UI interactions, math operations, and little operations, among other things.
  • Many tasks take a long time to complete, such as file downloads, database queries, and image upload/download.
  • If you execute these jobs on the main thread, they will take a long time to complete because they are long-running tasks, and your application will hang until then.
  • Because of this, your app may crash if it has been operating for a long time and the system considers it to be a non-responsive program.
  • Therefore, to perform these heavy tasks, you can create a worker or background thread that can handle these heavy tasks.
  • But the generation of these background threads is limited to certain limits because they are very memory intensive. If you create many such threads, you will run out of memory for other tasks, leading to a serious problem.
  • To fix this problem we have Coroutine option.
  • You can simply create a background thread and on it you can run multiple processes for tasks like file upload/download, database queries, network operations, etc.
  • Coroutines are very cheap to generate in terms of memory. These are lightweight threads.
  • They can work in parallel, they can wait for each other to complete the task and can communicate with each other.
  • Coroutines are similar to threads but It is not thread.

  • So this is a brief about the Coroutine, in the next post we can get idea how we can add the Coroutine in our Project to get started.