Scopes in Kotlin Coroutines
Last Updated :
05 Apr, 2025
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:
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.
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:
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.
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
Closures in Kotlin
According to Kotlin's official documentation "A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time the closure was created" var sum = 0 ints.f
2 min read
Local Functions in Kotlin
The idea behind functions is very simple: split up a large program into smaller chunks that can be reasoned more easily and allow the reuse of the code to avoid repetition. This second point is known as the DRY principle: Don't Repeat Yourself. The more the number of times you write the same code, t
5 min read
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
runBlocking in Kotlin Coroutines with Example
Prerequisite: Kotlin Coroutines on AndroidSuspend Function In Kotlin Coroutines As it is known that when the user calls the delay() function in any coroutine, it will not block the thread in which it is running, while the delay() function is called one can do some other operations like updating UI a
5 min read
Exception Handling in Kotlin Coroutines
Coroutines are a new way for us to do asynchronous programming in Kotlin in Android. When developing a production-ready app, we want to ensure that all exceptions are handled correctly so that users have a pleasant experience while using our app. In this article, we will discuss how to properly hand
7 min read