KOTLIN COROUTINES FOR ANDROID DEVELOPMENT
So welcome to another article part of my Kotlin series. I hoping that you guys are safe
So, this article is about
coroutines in Kotlin. Before we do a deep dive into what coroutines are I’d
like to us to know a few things about Kotlin
So, variables in Kotlin
are declared using the val or var keywords. The var keyword declares a mutable
value , that is it can be change later but if we use the val it means that the
value of our variable is immutable or that it cant be changed Also, we can use the lateinit keyword if we
want to declare a variable without initializing the variable.
Functions in all
programming languages generally are a sequence of instructions that take input
and give output
Threads are the contexts in
which our functions are executed in. All programs will by default execute
instructions one after the other unless otherwise specified.
COUROUTINES
Threading is important in
making software in some cases we may need more than one thread to execute our
programs. For example, in android apps the main thread is by default our UI
thread. Thus, having a thread that runs in the background to maybe make a
network call or post, what we call a worker thread is important for keeping our
UI responsive.
Now Coroutines are here
to solve the threading issue, Coroutines are like threads but way cooler. They
can be executed within a thread; they can switch the thread they run in and are
more lightweight than threads. Coroutines are also suspend able. They are always
started in a specific context, and that context describes in which threads the
coroutine will be started in. In general, we can start the coroutine using
Global Scope without passing any parameters to it, this is done when we are not
specifying the thread in which the coroutine should be launch. Using
GlobalScope means that the coroutine will run as long as the app or program is
running. Our coroutines can however use dispatchers
Dispatchers help coroutines to decide the thread on which
the work has to be done. Dispatchers are passed as the arguments to the Global Scope by mentioning which type of
dispatchers we can use depending on the work that we want the coroutine to
do. There are 4 main types of dispatchers. Main Dispatcher,
IO Dispatcher, Default Dispatcher, Unconfined Dispatcher
Main Dispatcher:
This will start the coroutine in the main thread. It is mostly used when we need to do UI operations within the coroutine. UI can only be changed from the main thread (also called the UI thread).
IO
Dispatcher:
It will start the
coroutine in the IO thread. We use it to perform all data operations such as
networking, reading, or writing from the database, reading, or writing to the
files
Default
Dispatcher:
It starts the
coroutine in the Default Thread. We choose this when we are planning to do
Complex and long-running calculations.
Unconfined
Dispatcher:
The unconfined
dispatcher is not confined to any specific thread. It executes the initial
continuation of a coroutine in the current call-frame and lets the coroutine
resume in whatever thread that is used by the corresponding function, without
mandating any specific threading policy.
The last cool thing about
Coroutines is Job. Anytime we launch a coroutine we actually return a job and
the terms coroutines and jobs can be used interchangeably.
We can control a job/coroutine
through the function available on the Job Interface. Some of the functions we
can use are start, join and cancel
Waiting for a coroutine
To wait for a coroutine to finish, you can call Job. join
. join
is a suspending
function. Meaning that the coroutine calling it will be suspended
until it is told to resume.
A suspending function is just a regular Kotlin
function with an additional suspend modifier which indicates
that the function can suspend the execution of a
coroutine. Suspending functions can invoke any other
regular functions, but to actually suspend the execution, it has
to be another suspending function. At the point of suspension, the executing thread is released to
any other available coroutines that are sharing that thread or thread pool. A thread pool is a software design
pattern for achieving concurrency of execution in a computer program. Often
also called a replicated workers or worker-crew model, a thread
pool maintains multiple threads waiting for tasks to be
allocated for concurrent execution by the supervising program.
Cancelling
a coroutine
It’s important to avoid doing more work than needed as
it can waste memory and system resources. This applies to coroutines also. we
must make sure that we control the life of the coroutine. The Cancel function
will help us to achieve this when it’s no longer needed.
Cancelling the entire scope in which our coroutines
are launched into will cancel all of the child coroutines created. Sometimes
you might need to cancel only one coroutine. Calling job.cancel on a
specific job ensures that only that specific coroutine gets cancelled and all
the other siblings are not affected.
Coroutines handle cancellation by throwing a special
exception: CancellationException
. If you want to provide
more details on the cancellation reason you can provide an instance of CancellationException
when callingcancel.
If you don’t provide your
own CancellationException
instance, a
default CancellationException
will be created
Below is
a simple code snippet to show you how coroutines work.
Coroutines are awesome I
suggest learning more on this topic. You can find out more on this on the link
given:
https://kotlinlang.org/docs/reference/coroutines-overview.html
Stay safe …. Keep coding.
Comments
Post a Comment