Skip to main content

Featured

What is Coroutine in Android?

Coroutines are available for the Kotlin language. Coroutines are simply cooperative functions.   Our Android applications often have multiple concurrent and interdependent functionalities. We provide instructions to the system through code, also known as a program, to perform a set of sequential instructions.  During the execution of these instructions, a specific instruction may take longer than expected, causing the next line of code to wait until the previous line of code has completed its execution. This scenario is known as blocking program execution. To avoid blocking program execution, the code must be executed on a separate thread. A thread is a single sequential flow of control. However, creating and handling multiple threads can be difficult and expensive in terms of OS operations and memory usage. To address this issue, we can use Coroutines in Kotlin. Coroutines are cooperative functions that are executed on threads as needed in a cooperative manner. They help manage long-r

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.

Comments

Popular Posts