AsyncTask in Android with Kotlin

前端 未结 10 1510
离开以前
离开以前 2020-12-13 12:31

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

10条回答
  •  無奈伤痛
    2020-12-13 13:07

    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() {
        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 {
        // ...
    }
    

提交回复
热议问题