cover-img

Suspend Function In Kotlin-Coroutines

Simple Function To Execute LongRunning Operations || Tasks Without Blocking, Which Can Be Paused && Resumed Later.

24 July, 2021

2

2

0

Contributors

Before Getting Started I Suggest You Understand What's Actually A Coroutine Is, Which I Have Discussed In The Previous Show. And Make Sure That You Have Included Coroutines Dependency If It's Not Included:
Suspend Function: Well, Suspend Function Is A Simple Function Which 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.

And The 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.
If You Are Trying To Implement delay() In Your Code, Your IDE May Show This Image In The Numerical Panel Where You Have Implemented A Suspend Function👇🏼
img

This Image Simply Means That You Are Implementing A Suspend Function.

As I Mentioned That delay() Is Also A Suspend Sunction Which Means That You Should Implement delay() In A Suspend Function Or In A Coroutine
->But In Case If You Are Trying To Implement Suspend Function Outside Of A Supend Function Or A Coroutine Leads To This Beautiful Error🤭:
->Error May Look Like This If You Are Trying To Implement Suspend Function Outside Of A Supend Function Or A Coroutine In Your Android Studio:
img
->Let's Build A Suspend Function In Android To Deep-dive:
->For Creating A Suspend Function We Need Mention suspend Before You Create The Function:
->Returning A String Value From The delaying() Function:
->As I Mentioned That Suspend Function Can Be Called || Implemented In Suspend Function Or In A Coroutine.
->Let's Launch A Coroutine By Assigning GlobalScope.launch{ } In Your Main Thread:
Note: You Should NOT Use GlobalScope every time.
->Now Let's Implement delaying() In Coroutine:
->Now If You Are Trying To Implement delaying() Outside, Of A Coroutine You'll Get This Error As delaying() Is A Suspend Function:
img
->Let's Assign LogTo Check If The delaying() Is Working Or Not:
->Now Run The Application And Open Logcat To Check The Result:
img
Well That's All For Now, In Upcoming Show I'll Discuss Coroutine Contexts😉

Bye🤗

android

android studio

coroutines

kotlin

suspend

2

2

0

android

android studio

coroutines

kotlin

suspend

Saketh
Composing Composable(s)!

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2025. Showcase Creators Inc. All rights reserved.