Kotlin: withContext() vs async-await — what's the difference and which to choose?
Hello, colleagues! I recently started learning coroutines in Kotlin, and I got confused between `withContext()` and the `async-await` construct. At first glance, both allow executing code in a different context (e.g., on `Dispatchers.IO`) and getting a result. But I don't understand when to use which.
Here's a simple example. Suppose I need to load data from the network and process it:
```kotlin
suspend fun loadUser(): User {
return withContext(Dispatchers.IO) {
// simulating a network request
delay(1000)
User("Alexey")
}
}
suspend fun loadUserAsync(): User {
val deferred = GlobalScope.async(Dispatchers.IO) {
delay(1000)
User("Alexey")
}
return deferred.await()
}
```
Both functions do the same thing — return a User after one second. But I've heard that `async-await` is often used for parallel tasks, while `withContext` is for switching dispatchers. However, in a simple sequential call, I don't see a difference.
Also, I noticed...
No answers yet.
Log in to leave an answer
Blogs