Home > Blockchain >  Do suspend functions suspend coroutines?
Do suspend functions suspend coroutines?

Time:08-07

I am confused actually. for example, I know suspendCoroutine function which is a suspend function that suspends a coroutine. but do all suspend functions suspend coroutines? in addition I know when a coroutine is suspended it remove from the corresponding thread for a while and other coroutines or tasks can resume and run on this thread.

I want to reach the conclusion that if all suspend functions do not suspend the coroutine, so what is the difference between put suspend function in the coroutine or a non-suspend function in the coroutine?

CodePudding user response:

Marking a function suspend gives it the capability to suspend the coroutine, but it will only actually suspend the coroutine if it internally calls another suspend function that suspends the coroutine. The suspend functions that directly suspend a coroutine are in the standard library. Among these are suspendCoroutine() and suspendCancellableCoroutine(). You will not often use these. They are most commonly used to convert non-coroutine APIs into suspend functions.

Some of the commonly used functions that indirectly suspend a coroutine are withContext(), delay(), Job.join() and Deferred.await().

  • Related