Android: (Part1) Introduction to Coroutines

Vinod Baste
CodeX
Published in
5 min readApr 3, 2022
source: google image

Android has a number of asynchronous programming techniques, but choosing the best one might be tricky. There is a steep learning curve for some systems. Others necessitate a lot of boilerplate code and aren’t very succinct. All of this has an impact on your app’s scalability and raises the cognitive burden for new developers. It’s ideal if the APIs you use is simple to use and grow as necessary.

Because all systems running on the JVM faced the same issue, the JetBrains team devised a new API. Its goal is to assist you in solving all of these issues without a high learning curve. — Kotlin Coroutines.

This series includes the following articles:

Why Should You Use Coroutines?

Every android application has a set of instructions that take much amount of time to process and bind the data to UI, so-called long-running tasks.

And all the bunch of code written executes in sequence on the main thread.

And by doing so long-running task on instruction 2 main freeze the application or halts the main thread until it executes completely which results in the bad behavior of the application.

But the coroutines made it super easy. It takes the long-running tasks on the top of the main thread i.e makes a mimick of it and executes without freezing or halting the main thread or other sequences of instructions.

You’ll also discover the following things along the way:

  • How Internally, Kotlin Coroutines work.
  • Learn how to build your own coroutines.
  • How Coroutines are used to handle exceptions.

To define Coroutines we need to understand :

Before we go into the implementation and use of coroutines, it’s vital to understand certain key points.

Coroutines Scope

A CoroutineScope keeps track of any coroutine it generates with the launch or async builder functions. It gives you the option of canceling a coroutine at any time. The scope is limited to a single life span. A coroutine can’t be started if it doesn’t have any scope. When a failure occurs, CoroutineScope is alerted.

KTX libraries for Android include a CoroutineScope in connection to lifecycle classes like viewModelScope and lifecycle scope.

Coroutines Context

It contains a coroutine dispatcher that selects which thread(s) the appropriate coroutine executes on.

The following parts make up a CoroutineContext, which determines the behavior of a coroutine:

  • Job: Manages the coroutine’s lifespan.
  • CoroutineDispatcher: Work is dispatched to the appropriate thread using CoroutineDispatcher.
  • CoroutineName: The coroutine’s name is useful for debugging.
  • CoroutineExceptionHandler: Uncaught exceptions are handled by the CoroutineExceptionHandler.

Dispatchers

Dispatchers are a way to define threads on which Coroutines are executed.

Some predefined dispatchers are:

  • Dispatchers.IO: Offloading blocking IO duties to a shared pool of threads and networking operations is the goal of the CoroutineDispatcher. On-demand, further threads in this pool are created and shut down.
  • Dispatchers.Main: A coroutine dispatcher that works with UI items and is limited to the main thread. You can use this dispatcher directly or through the MainScope factory. Typically, a single-threaded dispatcher is used.
    If no main thread dispatchers are available in the classpath, access to this property may result in an IllegalStateException.
  • Dispatchers.Default: If no dispatcher or other ContinuationInterceptor is given in its context, the default CoroutineDispatcher is utilized by all coroutine constructors such as launch, async, and others. It’s designed for off-the-main-thread CPU-heavy tasks.

suspend

Suspend is nothing more than a term. A suspend function is just that: a function that can be interrupted and resumed at a later time. We can perform long-running processes and wait for them to finish without having to block. Suspending functions use the same syntax as conventional functions, but with the addition of the suspend keyword.

suspend fun functionName() {
}

Note: Suspend should only be invoked from a coroutine or another suspend function, according to one fundamental requirement.

Job

A job is a terminable item with a life cycle that concludes with its completion. The launch coroutine builder is used to create a coroutine job. It executes a defined block of code and exits when it is finished.

The following are some of the many functions that the job interface provides:

  • join(): function is a suspending function, which means it can be invoked from within another suspending function or from a coroutine. Job suspends all threads until the coroutine in which it was written or the context in which it was written has completed its task. Only once the coroutine has been completed will the lines following the join() method be performed.
  • cancel(): method is used to terminate the coroutine without having to wait for it to complete its task. It is similar to the join method in that the join() method waits for the coroutine to complete its entire task before blocking all other threads, whereas the cancel() function kills, or stops, the coroutine when it is detected. Let’s look at an example that shows how the cancel() function works.
  • withTimeOut(): When a specified amount of time has passed, the coroutine will automatically be canceled and no further calculations will be performed, and withTimeOut() can aid with this.

Thank you for taking the time to read this article. If you found this post to be useful and interesting, please clap and recommend it.

if you got something wrong? Mention it in the comments. I would love to improve.

--

--