Search code examples
androidkotlinokhttp

How to make an Asynchronous OkHttp call inAndroid using Kotlin?


I am attempting to fetch API data with OkHttp using an inner class that inherits AsyncTask<Request, Void, Response>. Now when I try to initialize a response in the doInBackground(vararg params: Request?): Response method, I am forced to initialize the var response : Response? = null object like this, but I cannot set it to a nullable type, as the doInBackground() method expects a non-nullable Response. In Java, initializing Response was not mandatory. How do I circumvent this?

private class Fake : AsyncTask<Request, Void, Response>() {
        val client : OkHttpClient = OkHttpClient()
        override fun doInBackground(vararg params: Request?): Response{
            // Initialization is compulsory, and cannot be set to Response() as it is not accessible
            var response : Response? = null 
        }

    }

Solution

  • As you mentioned, using Kotlin so in that case, you can use retrofit which works with HTTP client and for performing in background thread use coroutine.

    It will perform API call in the background and update the Data on UI.

    For more reference please learn coroutine

    https://proandroiddev.com/using-retrofit-2-with-kotlin-coroutines-cb112f0fb738