• Home
  • Suspension functions can be called only within coroutine body – Android

Suspension functions can be called only within coroutine body – Android

A “suspension function” in the context of Android development refers to a specific type of function that is designed to be used within a coroutine. A coroutine is a concurrency construct that allows for a lightweight, non-blocking form of threading. Suspension functions are functions that are specifically built to be used within the context of a coroutine and can be used to perform tasks such as making network requests, waiting for user input, or performing long-running operations.

When you call a suspension function, the coroutine is suspended at that point and the function is executed. Once the function completes, the coroutine resumes where it left off. This allows for efficient and non-blocking execution of tasks.

The error message “suspension functions can be called only within coroutine body” is thrown when a suspension function is called outside of a coroutine. This means that the function was not called within the scope of a coroutine and it cannot be executed. To fix this error, the function should be called within a coroutine context, such as by wrapping the function call in a launch or async block.

In example:

suspend fun yourSuspendFunction(){
// do something here
}

fun main() = runBlocking {
launch {
yourSuspendFunction() // this will call your function without error
}
}

It’s important to note that the use of suspension functions is not limited to Android development. They are also used in the kotlinx.coroutines library which is available for other platforms and can be used in plain Kotlin projects as well.