Categories
Kotlin Android

Android Network Call using Kotlin coroutines

Kotlin coroutines makes network calls much easier. Specially all the async await like programming. Basically the biggest candidate before the coroutines were the asyncTask in Android. But thanks to the Kotlin coroutines we can easily do that task in much simpler way. In this example we are going to fetch a simple URL feed with just 3 functions.

Basically the coroutines does not create a seperate thread, instead they use existing threads efficiently with much efficient sheduling algorithm. So you can think coroutines as lightweight threads (Although they are not seperate threads).

At the end of the tutorial, we had placed some references for further reading.

The main motivation behind writing this post is because I found it little difficult to do a simple task using coroutines as all the examples and tutorials over internet were much complex. So I did a simple URL fetching task without any third party library like Volley (which I had used in one of my previous tutorial) or Reterofit or Okhttp etc.

Updating the Gradle

So let’s not waste time and dive into the android project. First of all open your build.gradle file and add follwoing two dependencies for the coroutines.

 implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0'
 implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0'Code language: JavaScript (javascript)

This is now not in experimental stage so no any further tweeking required in gradles.

Writing the Coroutines and Introduction to suspend keyword and Dispatchers

Next thing is the keyword suspend which needed to be prefixed with any function which you want to use as a coroutine. Just like we created this function

 // setting the launch mode during the function definition
    suspend fun getResults() = Dispatchers.Default {
        val result: String
          = URL("https:\\www.google.com").readText()
        // make network call
        return@Default result
    }
    // note the suspend modifier next to the fun keyword
    suspend fun makeNetworkCall(){
        // the getResults() function should be a suspend function too, more on that later
        val result = getResults()
        tvStatus.text = result
    }Code language: PHP (php)

Here you may notic that we had used a special thing called Dispatchers.Default. Bassically that is the thread which our coroutine will share while creating it’s scheduling job. There are Three main Dispatchers for specific jobs.

  • Dispatchers.Main
  • Dispatchers.IO
  • Dispatchers.Default

The reason of using the Dispatchers.Default is to make a combination of IO network request and GUI Update task (updating the textview) in single function. If we use Dispatchers.Main then the network IO would not be possible. And if we use Dispatchers.IO Then it will crash and complain if you try to do the UI updating task inside the function. So Dispatcher.Default will do our job without any complain.

Calling the Coroutine

Here is the final calling machanizm, for which we had created a global scope variable which will help us to cancel the network call if the app is being destroyed in between the calling. So this is how we created the variable and called the coroutine in onCreate function and finally cancell the job in onDestroy method. Here is the complete Activity code.

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle 
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import java.net.URL


class MainActivity : AppCompatActivity() {
    val scope = CoroutineScope(Job() + Dispatchers.Main)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tvStatus.text = "hello from programming"
       scope.launch {
           makeNetworkCall()
       }
    }


    // setting the launch mode during the function definition
    suspend fun getResults() = Dispatchers.Default {
        val result: String
          = URL("https:\\www.google.com").readText()
        // make network call
        return@Default result
    }
    // note the suspend modifier next to the fun keyword
    suspend fun makeNetworkCall(){
        // the getResults() function should be a suspend function too, more on that later
        val result = getResults()
        tvStatus.text = result
    }
    override fun onDestroy() {
        scope.cancel()
        super.onDestroy()
    }
}

References:

Here are the list of websites which I took help from while searching about the coroutines on Android

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.