chaosmonk
chaosmonk

Reputation: 417

How to properly make blocking service calls with Kotlin coroutines?

I am dealing with a http library (specifically one for making graphql calls) and it's API only offers blocking calls and is written in Java.

Now, I am writing my application with Kotlin and using the coroutines library, it got me wondering how should i make the blocking network call using coroutines.

So I have got this bit of code:

class DataService(val client: Client) {
    suspend fun getData(request: Request) {
        // process request

        client.makeServiceCall(...)

        //deal with response
    }
}

class Client() {
    suspend fun makeServiceCall(...) {
        library.query(....) //make a network call using the above mentioned library
    }
}

so I am wondering if Client.makeServiceCall() should be actually be marked as a suspending function because it does not actually suspend, it only blocks when it makes the network call. And how should i be making the call from DataService.getData() to makeServiceCall() and still adhere to the structured concurrency principles (like parent-child coroutine relationship)?

Upvotes: 4

Views: 7150

Answers (2)

Omega142
Omega142

Reputation: 313

Because the api you are using makes blocking calls doesn't necessarily mean that you need to adhere to that. If you are already using Kotlin coroutines you can easily use withContext(Dispatchers.IO to require a function to run on an IO thread. You absolutely should do this to avoid hanging the UI thread.

    suspend fun makeServiceCall(...) = withContext(Dispatchers.IO) {
        // This code now executes on a background thread and will not block the UI
        library.query(....) //make a network call using the above mentioned library
    }

Upvotes: 5

Asad Awadia
Asad Awadia

Reputation: 1521

Use withContext(Dispatchers.IO) in your makeServiceCall function

Upvotes: 2

Related Questions