Junior
How to run synchronous code and get its result?
sobes.tech AI
Answer from AI
You can use a blocking call in a separate thread, for example, via Thread or AsyncTask (although it is deprecated).
// Example with Thread
fun performBlockingOperation(): String {
// Simulate a long operation
Thread.sleep(2000)
return "Result of the synchronous operation"
}
fun runSynchronousCode() {
// Create a new thread
val thread = Thread {
try {
val result = performBlockingOperation()
// The result can be passed back to the main thread
// via Handler or runOnUiThread
println("Result received: $result")
} catch (e: Exception) {
println("Error: ${e.message}")
}
}
// Start the thread
thread.start()
// If you need to get the result back in the UI thread
// Handler(Looper.getMainLooper()).post {
// // UI update
// }
}
An alternative modern approach is to use coroutines with blocking dispatchers (although this may not be the best option for the UI thread).
import kotlinx.coroutines.*
suspend fun performBlockingCoroutineOperation(): String {
// Simulate a long operation
delay(2000)
return "Result of the synchronous operation in coroutine"
}
fun runBlockingCoroutine() {
// Launch a blocking coroutine
runBlocking {
try {
val result = performBlockingCoroutineOperation()
println("Result received from coroutine: $result")
} catch (e: Exception) {
println("Error in coroutine: ${e.message}")
}
}
}
It is important to avoid blocking calls on the main UI thread to prevent ANR (Application Not Responding).