In _Kotlin coroutines tips and tricks _series we are going to solve common real-life issues that might appear when coroutines are used in the code.

TL;DR
Wrap callbacks for asynchronous code with suspendCancellableCoroutine; code examples are available at the end of each chapter.

After playing around with Kotlin coroutines there is a good chance that you have encountered the following dilemma:

  • Writing suspend function.
  • Calling 3rd party asynchronous code that requires callback object with methods such as onSuccess and onFailure .
  • Needing results from callback to continue coroutine execution.

You probably already see the problem here, but let’s highlight it once again — we require results from _asynchronous _code within a synchronous block. Let’s take a look at the real-life example in the following section.

Example: Consuming purchased items using Google Billing API

Imagine we’re selling magic potions in our app that can be bought once at a time. Each time magic potion is purchased via Google Play Billing API it needs to be consumed in order to be available for repetitive purchase.

Per Billing API documentation, the developer must call [consumeAync(](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#consumeAsync)``) and provide an implementation of [ConsumeResponseListener](https://developer.android.com/reference/com/android/billingclient/api/ConsumeResponseListener).

ConsumeResponseListener object handles the result of the consumption operation. You can override the _onConsumeResponse()_ method of the ConsumeResponseListener interface, which the Google Play Billing Library calls when the operation is complete.

In order to notify our user that their magic potion was successfully added to the inventory, we need to check if Billing API has consumed purchased item. Let’s create an initial code draft

import com.android.billingclient.*;

	/**
	  * Consumes provided item
	  * @param billingClient initialized billing client
	  * @param consumerParams consume parameters with purchase token
	  * @return true if purchase is consumed, false otherwise
	 **/
	suspend fun consumeItem(
	 billingClient: BillingClient,
	 consumeParams: ConsumeParams
	): Boolean{
	  // Final result of consumption
	  var isConsumed: Boolean = false
	  // Consumption callback that will be called once Billing API finishes processing
	  val consumeResponseListener = ConsumeResponseListener { billingResult: BillingResult, purchaseToken: String ->
	     isConsumed = billingResult == BillingClient.BillingResponseCode.OK                                                    
	  }
	  // Calling Billing API to consume item
	  billingClient.consumeAsync(consumeParams, consumeResponseListener)
	  return isConsumed
	}

Initial code implementation for item consumption

Nice try, but once we run it we quickly discover that isConsumed is always false because return statement is called before consumeResponseListener has a chance to be called. Unfortunately, BillingClient doesn’t provide a _synchronous _way to consume item and we have to use callbacks. But there is a way to handle this — Kotlin coroutines allow to block code execution until further notice and we can use it to our advantage!

#callback #android #coroutine #kotlin

Synchronous Way to Work with Asynchronous Code.
12.45 GEEK