Junior — Middle
Kuidas käivitada Kotlinis peatatud funktsioon?
sobes.tech AI
Vastus AI-lt
In Kotlin, a suspend function does not start directly; it can only be called from another suspend function or from a coroutine. To start a suspend function, you need to create a coroutine using constructs like launch or async from the kotlinx.coroutines library.
Example of starting a suspend function:
import kotlinx.coroutines.*
suspend fun doWork() {
delay(1000)
println("Work completed")
}
fun main() = runBlocking {
launch {
doWork() // start suspend function inside a coroutine
}
}
Here, runBlocking creates a coroutine in the main thread, and launch starts a new coroutine in which the suspend function doWork is called. Thus, the suspend function runs inside a coroutine.