Synchronous Way to Work with Asynchronous Code.

Synchronous Way to Work with Asynchronous Code.

Synchronous Way to Work with Asynchronous Code. We are going to solve common real-life issues that might appear when coroutines are used in the code.

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

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Kotlin Coroutines on Android - How to use Coroutines on Android

Coroutines are a Kotlin feature that convert async callbacks for long-running tasks, such as database or network access, into sequential code. This Kotlin Coroutines tutorial will show you how to use coroutines on Android, and how the new androidx-concurrent library makes it easy to use them to get things off the main thread. You'll also learn how the new library helps coroutines work with Architecture Components. This session also covers coroutine patterns, best practices, and even how to test coroutines!

Top Android Projects with Source Code

Android projects with source code - Work on real-time android projects. We’ll start project ideas from beginners level and later move to advance projects.

How to Develop an Android App with Kotlin?

AppClues Infotech is a top Mobile App Development Company in USA building high-quality Android, iOS, and Native apps for Startups, SMBs, & Enterprises. Contact us now!

Top Kotlin Android App Development Company in USA

AppClues Infotech is a top Mobile App Development Company in USA building high-quality Android, iOS, and Native apps for Startups, SMBs, & Enterprises. Contact us now!

Top-notch Kotlin App Development Company in USA

AppClues Infotech is a top Mobile App Development Company in USA building high-quality Android, iOS, and Native apps for Startups, SMBs, & Enterprises. Contact us now!