Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java
  • Android
  • Kotlin
  • Flutter
  • Dart
  • Android with Java
  • Android Studio
  • Android Projects
  • Android Interview Questions
Open In App
Next Article:
Asynchronous Programming and Kotlin Coroutines in Android
Next article icon

Asynchronous Programming and Kotlin Coroutines in Android

Last Updated : 20 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Asynchronous programming is very important and it's now a common part of modern application. It increases the amount of work that an app can execute by allowing tasks to execute in parallel. This makes sure that heavy tasks run in the background, keeping the UI thread responsive and improving the overall user experience.

Kotlin Coroutines

The Kotlin team defines coroutines as “lightweight threads”. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a new style of concurrency that can be used on Android to simplify async code.

The official documentation says that coroutines are lightweight threads. By lightweight, it means that creating coroutines doesn't allocate new threads. Instead, they use predefined thread pools and smart scheduling for the purpose of which task to execute next and which tasks later.

Types of Coroutines

There are two types of Coroutines:

  • Stackless Coroutines - These do no maintain their own stack and do not map directly to native threads.
  • Stackful Coroutines - These maintain their own threads. (not used in Kotlin)

Kotlin implements stackless coroutines, meaning they operate without their own stack and are not directly tied to native threads.

Why Do We Need Coroutines?

As we know android developers today have many async tools in hand. These include RxJava, AsyncTasks, Jobs, Threads. But, these methods come with several challenges which includes:

  • RxJava - Safe Usage is complex and has a steep learning curve.
  • AsyncTasks & Threads - These can easily introduce leaks and memory overhead.
  • Callbacks - Complex, unreadable and excessive code.

Android is a single thread platform, By default, everything runs on the main thread. In Android, almost every application needs to perform some non UI operations like (Network call, I/O operations), so when coroutines concept is not introduced, what is done is that programmer dedicate this task to different threads, each thread executes the task given to it, when the task is completed, they return the result to UI thread to update the changes required. Though In android there is a detailed procedure given, about how to perform this task in an effective way using best practices using threads, this procedure includes lots of callbacks for passing the result among threads, which ultimately introduce tons of code in our application and the waiting time to get the result back to increases.

On Android, Every app has a main thread (which handles all the UI operations like drawing views and other user interactions. If there is too much work happening on this main thread, like network calls (eg fetching a web page), the apps will appear to hang or slow down leading to poor user experience.

Kotlin Coroutines Features

Coroutines is the recommended solution for asynchronous programming on Android. Some highlighted features of coroutines are given below.

  • Lightweight: One 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 frees memory over blocking while supporting multiple concurrent operations.
  • Built-in cancellation support: Cancellation is generated automatically through the running coroutine hierarchy.
  • Fewer memory leaks: It uses structured concurrency to run operations within a scope.
  • Jetpack integration: Many Jetpack libraries include extensions that provide full coroutines support. Some libraries also provide their own coroutine scope that one can use for structured concurrency.

Kotlin Coroutines vs Threads

Features

Threads

Coroutines

Resource Usage

Heavyweight (high memory/CPU usage)

Lightweight(thousands can run on a single thread)

Context Switching

Slower, as it depends on thread completion

Faster, as coroutines can suspend and resume

Parallelism

Native OS-supported parallelism (runs on multiple cores)

Single threaded by default by can be Multi-threaded via dispatchers.

Creation Cost

High (Each thread has its own stack)

Low (coroutines do not require separate stacks)

Readability

Complex (Involves multiple callbacks)

Simplified (More concise and readable code)

Scaling

Limited by OS/hardware (hundreds of threads risk instability)

Scales effortlessly to thousands of concurrent operations

Kotlin Coroutines Dependencies

Add these dependencies in build.gradle.kts Module-level file.

Kotlin
dependencies {   implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-core:x.x.x")   implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-android:x.x.x") } 

Note: Replace x.x.x with the latest coroutine version. As of Feb 2025, the latest and stable version of Kotlin Coroutines is 1.10.1

Kotlin Coroutines Example

Let's say we want to fetch some users from the database and show it on the screen. For fetching the data from the database we have to perform the network call, fetch the user from the database, and show it on the screen. Fetching the user can be done by using either by using callbacks or coroutines.

Using Callbacks:

Less readable code

Kotlin
fun fetchAndShowUser() {   fetchUser   {     user -> showUser(user)   } } 

Using Coroutines:

This has a more cleaner code

Kotlin
suspend fun fetchAndShowUser() {   val user = fetchUser()    showUser(user) } 

As discussed above using callbacks will decrease the code readability, so using coroutines is much better to use in terms of readability and performance as well. As discussed above Coroutines has many advantages apart from not having callbacks, like they are nonblocking, easy, and nonexpensive to create.       


Next Article
Asynchronous Programming and Kotlin Coroutines in Android

L

lavishgarg26
Improve
Article Tags :
  • Kotlin
  • Android
  • Kotlin Android

Similar Reads

    Retrofit with Kotlin Coroutine in Android
    Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as “lightweight threads”. They are sort of tasks that the actual threads can e
    3 min read
    Launch vs Async in Kotlin Coroutines
    The Kotlin team defines coroutines as “lightweight threads”. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a new style of concurrency that can be used
    4 min read
    Jobs, Waiting, Cancellation in Kotlin Coroutines
    Prerequisite: Kotlin Coroutines On AndroidDispatchers in Kotlin CoroutinesSuspend Function In Kotlin Coroutines In this article, the following topics will be discussed like what are the jobs in a coroutine, how to wait for the coroutine, and how to cancel the coroutine. Whenever a new coroutine is l
    7 min read
    What is Flow in Kotlin and How to use it in Android Project?
    To build an app asynchronously we have to use RxJava and it is also one of the most important topics in Android Development. But now in Kotlin Jetbrains came up with Flow API. With Flow in Kotlin now we can handle a stream of data sequentially. Flow is a stream processing API in Kotlin developed by
    4 min read
    Unit Testing of ViewModel with Kotlin Coroutines and LiveData in Android
    The official documentation says that coroutines are lightweight threads. By lightweight, it means that creating coroutines doesn’t allocate new threads. Instead, they use predefined thread pools and smart scheduling for the purpose of which task to execute next and which tasks later. In this article
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences