Search code examples
kotlin-coroutinesplay-billing-library

Why does the querySkuDetails need to run in IO context?


According to https://developer.android.com/google/play/billing/integrate the billingClient.querySkuDetails is called with withContext(Dispatchers.IO)

fun querySkuDetails() {
    val skuList = ArrayList<String>()
    skuList.add("premium_upgrade")
    skuList.add("gas")
    val params = SkuDetailsParams.newBuilder()
    params.setSkusList(skuList).setType(SkuType.INAPP)
    val skuDetailsResult = withContext(Dispatchers.IO) {
        billingClient.querySkuDetails(params.build())
    }
    // Process the result.
}

I am curious which benefits it gives as querySkuDetails is already a suspending function. So what do i gain here.

I could write the same code with

val skuDetailsResult = coroutineScope {
        billingClient.querySkuDetails(params.build())
}

There is no more context and i don't know how to download the source code of the billing client.


Solution

  • The underlying method being called is querySkuDetailsAsync which takes a callback and performs the network request asynchronously.

    You are correct that withContext(Dispatchers.IO) is not needed there, it actually introduces unnecessary overhead.

    Gotten from https://stackoverflow.com/a/62182736/6167844

    It seems to be a common misconception, that just because IO is being performed by a suspend function, you must call it in Dispatchers.IO, which is unnecessary (and can be expensive).

    suspending functions by convention don't block the calling thread and internally blocks in Dispatchers.IO if need be.