Axel
Axel

Reputation: 5131

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?

Upvotes: 2

Views: 9385

Answers (1)

Sergio
Sergio

Reputation: 30745

createRequest() is a suspend function and it must be called from a coroutine or another suspend function. 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 of Deferred.

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())
}

Upvotes: 0

Related Questions