Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask in Android with Kotlin

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.

like image 630
Rakesh Gujari Avatar asked Jun 13 '17 15:06

Rakesh Gujari


People also ask

What is AsyncTask in Android with example?

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 .

What can I use instead of AsyncTask in Kotlin?

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.

What is the use of AsyncTask class in Android?

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.

What is difference between service and AsyncTask in Android?

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.


1 Answers

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:

  • https://github.com/Kotlin/anko/blob/d5a526512b48c5cd2e3b8f6ff14b153c2337aa22/anko/library/static/commons/src/Async.kt

If you use Anko your code will be similar to this:

doAsync {     // ... } 
like image 80
shiftpsh Avatar answered Sep 28 '22 07:09

shiftpsh