Home > OS >  Why use suspend functions in kotlin coroutine?
Why use suspend functions in kotlin coroutine?

Time:10-20

Why we should use suspend? Are they used only to restrict a function not to be used outside coroutine scope or other suspend functions?

CodePudding user response:

If you wonder what it does, I guess you will find the answer in this near-duplicate question's answer. It basically allows to use the syntax of synchronous calls to call an asynchronous function.

If the question is "Why use async programming?", then there are probably plenty of resources explaining this on the internet. It usually allows to use threads more effectively and avoids using too many resources.

Now as to why you would want to use suspend to do that instead of callbacks, there is probably several reasons. Probably the biggest of them is to avoid the infamous "callback hell": using actual callbacks creates nesting in the code. It makes the language harder to manipulate because you can't use local variables or loops as easily as with regular sequential code.

Another big reason to use suspend (and more precisely the coroutines library in general) is structured concurrency. It allows to organize your asynchronous work so you don't leak anything.

CodePudding user response:

Are they used only to restrict a function not to be used outside co routine scope or other suspend functions?

No. The main purpose of a suspend function is to suspend a coroutine it is called in to eliminate callback hell. Consider the following code with a callback:

fun interface Callback {
    fun call()
}

fun executeRequest(c: Callback) {
    // ... create new Thread to execute some request and call callback after the request is executed
    c.call()
}

On the caller side there will be:

executeRequest {
    // ... do sth after request is competed.
}

Imagine you need to make another request after that one:

executeRequest {
    // make another request
    executeRequest {
        // and another one
        executeRequest {
            // and another one ...
            executeRequest {

            }
        }
    }
}

That is a Callback Hell. To avoid it we can get rid of a Callback code and use only suspend functions:

// withContext(Dispatchers.IO) switches a coroutine's context to background thread
suspend fun executeRequest() = withContext(Dispatchers.IO) {
    // just execute request, don't create another Thread, it is already in the background Thread
    // if there is some result, return it
}

And on the caller side if there are a couple of requests, that should be executed one by one, we can call them without the Callback Hell by launching a coroutine and calling those request in the coroutine:

viewModelScope.launch {
    executeRequest()
    executeRequest()
    executeRequest()
}
  • Related