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:
Scopes in Kotlin Coroutines
Next article icon

Scopes in Kotlin Coroutines

Last Updated : 05 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Scope in Kotlin's coroutines can be defined as the restrictions within which the Kotlin coroutines are being executed. Scopes help to predict the lifecycle of the coroutines. Kotlin CoroutinesScope is a term well used in the referred for the interface used for defining the Scope(lifetime and context) in which coroutines are launched.

There are basically 3 scopes in Kotlin coroutines:

  • Global Scope
  • LifeCycle Scope
  • ViewModel Scope

Dependencies to be Imported in Build.gradle (app level file)

Import following dependencies to build.gradle (app) level file.

XML
// Coroutines implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.1' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1'  // Lifecycle components implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.2' implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.2' implementation 'androidx.activity:activity-ktx:1.7.2' 


 

1. Global Scope

Global Scope is one of the ways by which coroutines are launched. When Coroutines are launched within the global scope, they live long as the application does. If the coroutines finish it's a job, it will be destroyed and will not keep alive until the application dies, but let's imagine a situation when the coroutines has some work or instruction left to do, and suddenly we end the application, then the coroutines will also die, as the maximum lifetime of the coroutine is equal to the lifetime of the application. Coroutines launched in the global scope will be launched in a separate thread.

Below is the example which shows that the in global scope coroutines are launched in a separate thread.

Kotlin
import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch  class MainActivity : AppCompatActivity() {     val TAG = "Main Activity"          override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)                  GlobalScope.launch {             Log.d(TAG, Thread.currentThread().name.toString())         }                  Log.d("Outside Global Scope", Thread.currentThread().name.toString())     } } 

 
Below is the Log-Output for the above program:

GlobalScope


 

As it is known that coroutines launched in global scope live as long as the application does, but there are very rare chances when the developer needs the coroutines to be live as long as the application does. The main problem with the coroutines launched in the global scope is that when the activity in which coroutines is launched dies, the coroutines will not die with the activity, since the lifetime of coroutines is decided on the basis of application lifetime, not the activity lifetime. Since the coroutine is using the resources of the activity in which it is launched, and now since that activity has died, the resources will not be garbage collected as a coroutine is still referring to that resources. This problem can lead to a memory leak. So using global scope all the time is not always a good idea. Let's try to launch a coroutine and run an infinite loop with a delay of 1 sec and launch another coroutine within the global scope after the delay of 5 sec from the starting by terminating the first activity and intent to another activity. we can see in the output that even after the first activity is being terminated programmatically, the coroutine associated with the first activity does not die. Let's try to understand what written in the above paragraph programmatically.

Below is the code for both the activity_main.xml and the MainActivity.kt file.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <Button         android:id="@+id/btnStartActivity"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginStart="167dp"         android:layout_marginTop="320dp"         android:layout_marginEnd="156dp"         android:layout_marginBottom="363dp"         android:text="Start Activity"         android:textSize="22sp"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout> 
MainActivity.kt
// Program for main activity which intent to another activity // it uses global scope to launch the coroutine package com.gfg.coroutines  import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Button import androidx.appcompat.app.AppCompatActivity import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.launch  const val TAG = "Main Activity"  class MainActivity : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?) {              super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          val btnStartActivity = findViewById<Button>(R.id.btnStartActivity)          btnStartActivity.setOnClickListener {              // coroutine will launch when button got pressed             GlobalScope.launch {                  // infinite loop                 while (true) {                     delay(1000L)                     Log.d(TAG, "Still Running..")                 }             }              GlobalScope.launch {                 delay(5000L)                  // new activity will get intended after 5 sec                 val intent = Intent(this@MainActivity, SecondActivity::class.java)                 startActivity(intent)                 // calling finish() method,so that first activity will not be alive                 // after being intended to second activity                 finish()             }         }     } } 

 
Go to app > java > 1st package name > right-click > New > Activity > Empty Activity to create a new activity and named it as SecondActivity.

Below is the code for both the activity_second.xml and SecondActivity.kt file.

activity_second.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".SecondActivity">      <!--Various attributes for button-->     <Button         android:id="@+id/btnSecondActivity"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginStart="166dp"         android:layout_marginTop="331dp"         android:layout_marginEnd="130dp"         android:layout_marginBottom="352dp"         android:gravity="center"         android:text="Second Activity"         android:textSize="22sp"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout> 
SecondActivity.kt
// Program for second activity package com.gfg.coroutines  import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.isActive  class SecondActivity : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_second)                  Log.i("Second Activity", "Second Activity Running ....")         Toast.makeText(this, "Second Activity", Toast.LENGTH_SHORT).show()          GlobalScope.isActive     } } 

 
 Output: 


It can be seen in the log out below that even after the second activity is being launched, the coroutine of the main activity is still running. The oval circle is used to show the timestamps.

GlobalScope4


2. Lifecycle Scope

The lifecycle scope is the same as the global scope, but the only difference is that when we use the lifecycle scope, all the coroutines launched within the activity also dies when the activity dies. It is beneficial as our coroutines will not keep running even after our activity dies. In order to implement the lifecycle scope within our project just launch the coroutine in lifecycle scope instead of global scope, i.e. just change the global scope to lifecycle scope in the main activity within which the infinite loop is running.

All the code will remain the same except for some changes in the code of the main activity as mentioned above.

MainActivity.kt:

MainActivity.kt
// Program to show how lifecycle scope works package com.gfg.coroutines  import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch  const val TAG = "Main Activity"  class MainActivity : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          val btnStartActivity = findViewById<Button>(R.id.btnStartActivity)          btnStartActivity.setOnClickListener {                          // launching the coroutine in the lifecycle scope             lifecycleScope.launch {                 while (true) {                     delay(1000L)                     Log.d(TAG, "Still Running..")                 }             }              GlobalScope.launch {                 delay(5000L)                 val intent = Intent(this@MainActivity, SecondActivity::class.java)                 startActivity(intent)                 finish()             }         }     } } 

 
 Log Output: 

GlobalScope4

It can be seen in the above log output that the main activity stops get printing after the launch of the second activity.


3. ViewModel Scope

viewModelScope is also the same as the lifecycle scope, only difference is that the coroutine in this scope will live as long the view model is alive. ViewModel is a class that manages and stores the UI-related data by following the principles of the lifecycle system in android.

Features of viewModelScope in Android

There are few key features with viewModelScope mentioned below:

  • It cancels the coroutine when ViewModel is destroyed.
  • Uses Dispatcher.Main by default but can be changed context with withContext.
  • All the coroutines will be cleared when onCleared() Method is called, also cancel() can be used for this.

 


Next Article
Scopes in Kotlin Coroutines

L

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

Similar Reads

    withContext in Kotlin Coroutines
    Prerequisite: Kotlin Coroutines on AndroidLaunch vs Async in Kotlin Coroutines It is known that async and launch are the two ways to start the coroutine. Since It is known that async is used to get the result back, & should be used only when we need the parallel execution, whereas the launch is
    3 min read
    Suspend Function In Kotlin Coroutines
    Prerequisite: Kotlin Coroutines on Android 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
    4 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
    Kotlin - Scope Function
    There are several functions in the Kotlin standard library that help in the execution of a block of code within the context of an object. Calling these functions on an object with lambda expression creates a temporary scope. These functions are called Scope Functions. We can access the object of the
    7 min read
    Dispatchers in Kotlin Coroutines
    Prerequisite: Kotlin Coroutines on Android It is known that coroutines 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 GlobalScope without passing any parameters to it, this is done w
    3 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