A Brief Introduction to Coroutines With Example

by | Dec 31, 2020 | Development, Tips | 0 comments

    Software engineers have to address some problems that are common within an application under development. They use design patterns such as Singleton and various other design patterns. Similarly, there are design patterns for concurrency as well. Coroutines is one such design pattern used in Android development. This design pattern is for simplification of code that is executed asynchronously. Coroutines were introduced in Kotlin in version 1.3. They are based on concepts from other programming languages. 

    There can be multiple tasks (threads) running at the same time on Android. An app becomes unresponsive when a long-running task blocks the main task. Coroutines help in managing such long-running tasks. Over 50% of Android developers enjoy increased productivity with coroutines. This design pattern facilitates cleaner and concise code.


    Coroutines 

    The word ‘Coroutines’ is a combination of ‘Co’ and ‘Routines’. Here:

    • Co means cooperation   
    • Routines means functions

    Coroutines means cooperation between functions. 

    Coroutines functions

    Consider the following code as an example. In this code, we use two functions including functionA and functionB.   

    functionA as below:

    fun functionA(case: Int) {

        when (case) {

            1 -> {

                taskA1()

                functionB(1)

            }

            2 -> {

                taskA2()

                functionB(2)

            }

            3 -> {

                taskA3()

                functionB(3)

            }

            4 -> {

                taskA4()

                functionB(4)

            }

        }

    }

    And functionB as below:

    fun functionB(case: Int) {

        when (case) {

            1 -> {

                taskB1()

                functionA(2)

            }

            2 -> {

                taskB2()

                functionA(3)

            }

            3 -> {

                taskB3()

                functionA(4)

            }

            4 -> {

                taskB4()

            }

        }

    }

    Call the functionA as functionA(1). The functionA will execute taskA1 and functionB gets control for the execution of the taskB1. After the completion of the taskB1, the functionB will give control to the functionA for the execution of taskA2 and so on.   

    As you can see in the code that both functions cooperate. Kotlin coroutines makes this cooperation easy without using when or switch case as you can see in the given example. 

    This example shows that coroutines make multitasking much easier. Both the threads and coroutines are multitasking. The difference is that coroutines are controlled by the developer and threads are managed by the operating system. Developers use coroutines to execute a few lines of code. 

    The cooperative nature of functions makes this framework written over actual threading light and yet powerful. Coroutines are lightweight and faster threads. They don’t require context switching as they don’t map on the native thread.

    Features 

    App developers are recommended to use coroutines for asynchronous programming. The following are key features:

    ey features:    

    • Lightweight   

    The support for suspension allows you to run multiple coroutines on single thread. Suspension does not block a thread on which coroutine is running. This supports multiple concurrent operations and at the same time, saves memory.

    • Built-in Support for Cancellation   

    It automatically propagates cancellation through the running coroutine hierarchy. 

    • Fewer Memory Leaks

    It allows running operations within a scope using structured concurrency. 

    • Jetpack Integration

    Extensions included in Jetpack libraries provide full support for coroutines. You can also use coroutine scope provided by some libraries for structured concurrency.

    Let’s understand this with a real life example.

    Imagine you have to parse data from 100 sites. It requires making a call for each of the 100 sites. After you receive the response, you do something with the data received from 100 sites. You can start 20 threads with multithreading in a pool. Each thread uses memory, sends a request before sleeping. After finishing, some threads return to the pool and make another call before sleeping only. As you can see, you are making all 100 calls simultaneously in one thread. 


    Dependency Info 

    You need to add the following dependency to the build.gradle file of the app to use coroutines in an app under development: 

    dependencies {

        implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9’

    }