'How to correctly perform a http request with Kotlin Coroutines?
So, I have a following function which does a basic request using Ktor client to get a list of users,
suspend fun createRequest(): List<User>? {
return withContext(Dispatchers.IO) {
try {
val client = HttpClient(CIO)
val response: HttpResponse = client.get("http://10.0.2.2:9999/users")
client.close()
val str = response.readText()
val itemType = object : TypeToken<List<User>>() {}.type
Gson().fromJson<List<User>>(str, itemType)
} catch (e: Exception) {
null
}
}
}
Now, I use this as following,
runBlocking {
val res = async {createRequest()}
val users = res.await()
Log.v("_APP_", users.toString())
}
But then I read runBlocking should be used in testing and debugging and is not recommended for production. then what do I use instead of runBlocking?
Solution 1:[1]
createRequest() is a suspend function and it must be called from a coroutine. There are a couple of coroutine builders:
runBlocking- It is not recommended for production because it blocks the current thread.launch- launches a new coroutine concurrently with the rest of the code, which continues to work independently.async- creates a coroutine and returns its future result as an implementation ofDeferred.
In Android there are a couple of ways to launch a coroutine, please refer to these docs.
To launch a coroutine you should have an instance of CoroutineScope, it can be viewModelScope (from the docs), lifecycleScope (from the docs) or custom instance. The sample code will look similar to:
scope.launch {
val users = createRequest()
Log.v("_APP_", users?.toString())
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BigSt |
