How to fix "Inappropriate blocking method call" error in OkHttp and Kotlin coroutines?
Hi! I'm a beginner Kotlin developer and trying to make an HTTP request using OkHttp inside a coroutine. I have this code:
```kotlin
suspend fun fetchData(): String {
val client = OkHttpClient()
val request = Request.Builder()
.url("https://api.example.com/data")
.build()
val response = client.newCall(request).execute() // Error here!
return response.body?.string() ?: ""
}
```
But the compiler or linter (Detekt, IntelliJ IDEA) gives a warning: "Inappropriate blocking method call". I'm using coroutines for asynchrony, but the `execute()` method blocks the current thread. How can I properly make an HTTP request in a coroutine without blocking the thread? I've heard about `suspendCancellableCoroutine`, but I don't understand how to apply it. I'm also using
No answers yet.
Log in to leave an answer
Blogs