34
loading...
This website collects cookies to deliver better user experience
Make Sure
That You Have Included Coroutines Dependency If It's Not Included:implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
Can Be Paused
And Resumed Later In Your Code
.Suspend Function Can Execute Long-Running Operations || Tasks And Will Wait For It To Complete Without Blocking The Whole Code.
Speciality
Of Suspend Function Is That It Can Be Only Implemented In Another Suspend Function || Coroutine
. delay()
Is Also A Suspend Function That delays the coroutine for a specific time.delay()
In Your Code, Your IDE May Show This Image
In The Numerical Panel Where You Implemented A Suspend Function
👇🏼This Image Simply Means That You Are Implementing A Suspend Function.
delay()
Is Also A Suspend Sunction
Which Means That You Should Implement delay()
In A Suspend Function
Or In A Coroutine
Outside Of A Supend Function Or A Coroutine
Leads To This Beautiful Error🤭
:Suspend function 'delay' should be called only from a coroutine or another suspend function
suspend
Before You Create The Function:suspend fun delaying() {
//Code
}
delaying()
Function:suspend fun delaying():String{
return "Stay Safe😷"
}
Suspend Function Can Be Called || Implemented In Suspend Function Or In A Coroutine
.GlobalScope.launch{}
In Your Main Thread:override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
GlobalScope.launch {
//Code
}
}
suspend fun delaying():String{
return "Stay Safe😷"
}
Note:
You Should NOT
Use GlobalScope every time.delaying()
In Coroutine:GlobalScope.launch {
delaying()
}
delaying()
Outside, Of A Coroutine You'll Get This Error As delaying()
Is A Suspend Function:GlobalScope.launch {
val checking=delaying()
Log.d("suspend", "${checking} Is Running In ${Thread.currentThread().name}")
}
suspend fun delaying():String{
delay(2000L)
return "Stay Safe😷"
}
Bye🤗