How to make an API call in Android with Kotlin?
I have heard of Anko . But I want to use methods provided by Kotlin like in Android we have Asynctask for background operations.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .
Alternative 1: Using Executor and Handler The executor will help in performing any task in the background and the handler will help to make UI changes.
Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive. Android application runs on a single thread when launched.
service is like activity long time consuming task but Async task allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.
AsyncTask
is an Android API, not a language feature that is provided by Java nor Kotlin. You can just use them like this if you want:
class someTask() : AsyncTask<Void, Void, String>() { override fun doInBackground(vararg params: Void?): String? { // ... } override fun onPreExecute() { super.onPreExecute() // ... } override fun onPostExecute(result: String?) { super.onPostExecute(result) // ... } }
Anko's doAsync
is not really 'provided' by Kotlin, since Anko is a library that uses language features from Kotlin to simplify long codes. Check here:
If you use Anko your code will be similar to this:
doAsync { // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With