Sobes.tech
Junior — Middle

How can you perform an asynchronous code block inside a synchronous function when using Coroutines?

sobes.tech AI

Answer from AI

In Kotlin Coroutines, to execute an asynchronous block of code inside a synchronous function, you can use the runBlocking function. It launches a coroutine and blocks the current thread until its completion.

Example:

fun syncFunction() {
    runBlocking {
        // Asynchronous code inside
        val result = async {
            // some suspend function
            delay(1000)
            "Result"
        }.await()
        println(result)
    }
}

Thus, runBlocking allows calling suspend functions from a synchronous context and waiting for their result without making the function suspend.

Be careful with runBlocking, especially in Android UI threads, to avoid UI freezes. Usually, for async work in Android, suspend functions or coroutines launched in appropriate contexts (like lifecycleScope) are used.

How can you perform an asynchronous code block inside… - sobes.tech