Coroutines

Coroutine async and await example

Pinterest LinkedIn Tumblr

In this blog, I’ll show you uses of async and await function in coroutine. We’ll learn async and await coroutine functions with example. So let’s started.

Objective

The async is basically another way to start a Coroutine. Sometimes when you start a coroutine, you might need a value to be return from that coroutine back to the thread that launched it. So async just like launch, except it return a result.

Now the results, obviously since it’s returning in parallel, It can not return immediately. so think about an operation like network communication might have undetermined delay. But we still want to have that resolved that outcome at some point. So what async does, is return a result in the form of a deferred.

So deferred is basically promise that at the some point we will be able to get result but it’s not available right now. So it’s a future promise of a value.

async function

So this question is when we actually need the value, we have the await function. Important things is, this is a blocking call. It done on purpose obviously because at certain points we do need the value we can not proceed without it. So we have to wait for that value to be available.

So either the value is available straight away which is return immediately or If in value is not available it will pause the current thread until it is. So you can say If the value is available, it will return immediately or If the value is not available, it will pause the thread until it is, as simple as that. For achieving this functionality we have await function in coroutine.

How use await function

It a quite simple, so let say we have one suspended function that gives a random integer number. Now would have aync coroutine. So we have a GlobalScope.aysnc just like below. This will launch a coroutine that simply return call the suspended function.

suspend fun getRandom() = Random.nextInt(1000)

val valueDeferred = GlobalScope.async { getRandom() }
… // Do some processing here
val finalValue = valueDeferred.await( )

So it will give us a deferred. So this is the object of deferred then we do whatever processing we need in that program. Then we actually need the value we have to await() function. So this will pause the execution until the value is available for our main program. So we are simply waiting for a value to be available.

Example of async and await

Let’s take one example for better understanding. Let suppose you want to call a APIs right. For calling that API you might need some auth token. For example you might need API key and Access Token for calling API. It not a useful or a practical example but explain async concept, Its perfect.

So here I simply creating a runBlocking. and define 3 functions. these are below.

package com.asyncawaitexamplecoroutine

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlin.random.Random

class MainActivity : AppCompatActivity() {
    companion object {
        private const val TAG = "MainActivity"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        runBlocking {
            val accessTokenDeferred = async { getAccessToken() }
            val apiKeyDeferred = async { getApiKey() }

            Log.i(TAG,"Doing some processing here")
            delay(500L)
            Log.i(TAG,"Waiting for values")

            val firstValue = accessTokenDeferred.await()
            val secondValue = apiKeyDeferred.await()

            textView.append("Access Token -> $firstValue \n")
            textView.append("API Key  -> $secondValue \n")
            textView.append(" User Details -> " + getUserDetails(firstValue,secondValue) )

        }
    }
    private suspend fun getAccessToken(): String {
        delay(1000L)
        val value = "ffe20d1e-bb7d-48c6-95a4-7d0f1fde26ab"
        Log.i(TAG,"Returning AccessToken $value")
        return value
    }

    private suspend fun getApiKey(): String {
        delay(2000L)
        val value = "ca6ee68b-73b8-41e1-8920-d20e349e36b6"
        Log.i(TAG,"Returning API key $value")
        return value
    }
    private suspend fun getUserDetails(accessToken:String, apiKey:String): String {
        delay(2000L)
        Log.i(TAG, " Access Token -> $accessToken API key ->$apiKey")
        val value = " Morris Kushwaha"
        Log.i(TAG,"Returning user details $value")
        return value
    }
}

It’s pretty straight forward, getAccessToken() and getApiKey() is aysnc in scope of run blocking. After that will call getUserDetails() function. In this function we simply logging access token and api and returning a value. So Important thing is we are waiting for a result from the first coroutine which will take 1 second.

Then second value is going to be deferred and it taking 2 second. After this simply calling userDetails function, that all. Let run this code and see this output

Output

I/MainActivity: Doing some processing here
I/MainActivity: Waiting for values
I/MainActivity: Returning AccessToken ffe20d1e-bb7d-48c6-95a4-7d0f1fde26ab
I/MainActivity: Returning API key ca6ee68b-73b8-41e1-8920-d20e349e36b6
I/MainActivity:  Access Token -> ffe20d1e-bb7d-48c6-95a4-7d0f1fde26ab API key ->ca6ee68b-73b8-41e1-8920-d20e349e36b6
I/MainActivity: Returning user details  Morris Kushwaha

So in logcat we get are Doing some processing here first after that Waiting for values. And getting AccessToken and after two second API key and finally Returning user details.

Conclusion

So basically async is a way for us to retrieve values from Coroutine. That all, so in this coroutine async and await example we’ll learned how we’ll make async call using Coroutine in android. I hope it’s helpful for you, Help me by sharing this post with all your friends who learning android app development.

Coroutine related article

FAQ

1 Comment

Write A Comment