Coroutines – A wonder of Android Development

Acoroutine is a concurrency design pattern that we can use on Android to simplify code that executes asynchronously. On Android, coroutines help to manage long-running tasks that might otherwise block the main thread and cause our app to become unresponsive. Over 50% of professional developers who use coroutines have reported seeing increased productivity.

Features

Coroutines is recommended solution for asynchronous programming on Android. Noteworthy features include the following:

  • Lightweight: You can run many coroutines on a single thread due to support for suspension, which doesn’t block the thread where the coroutine is running. Suspending saves memory over blocking while supporting many concurrent operations.
  • Fewer memory leaks: Use structured concurrency to run operations within a scope.
  • Built-in cancellation support: Cancellation is propagated automatically through the running coroutine hierarchy.
  • Jetpack integration: Many Jetpack libraries include extensions that provide full coroutines support. Some libraries also provide their own coroutine scope that you can use for structured concurrency.

Simply speaking –

  1. They are cheap.
  2. Increases code readability.
  3. Configuration setup is less (as compared to RxJava) for simple tasks.

Coroutines build upon regular functions by adding two operations to handle long-running tasks. In addition, to invoke (or call) and return, coroutines add suspend and resume:

  • suspend pauses the execution of the current coroutine, saving all local variables.
  • resume continues execution of a suspended coroutine from the place where it was suspended.

You can call suspend functions only from other suspend functions or by using a coroutine builder such as Launch to start a new coroutine.

Suspending functions are what the name hint: they are function that can pause the execution of the code and resume it later when the function is completed; this allows you to write code that feels more natural.

Exit mobile version