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.

推荐答案

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并不是Kotlin真正"提供"的,因为Anko是一个库,它使用Kotlin的语言特性来简化长代码.点击这里:

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

doAsync {
    // ...
}

Kotlin相关问答推荐

在KMM合成多平台中创建特定于平台的视图

将文本与文本字段的内容对齐

用Quarkus和Reactor重写异步过滤器中的数据流

Kotlin 复制列表中的项目以创建具有相同数据的不同对象的新列表

Spring Boot Kotlin 数据类未使用 REST 控制器中的默认值初始化

Kotlin:伴随对象内的函数扩展

即使 Kotlin 的 `Map` 不是 `Iterable`,它如何以及为什么是可迭代的?

Mixin 在 Jackson 中添加 defaultImpl 不起作用

Kotlin:如何使用第一个参数的默认值进行函数调用并为第二个参数传递一个值?

runOnUiThread 没有调用

如何设置两列recyclerview?

将协同路由调用放在存储库或ViewModel中哪个更好?

Jetpack Compose – LazyColumn 不重组

API 26 上未显示 Android 通知

重复构建失败To use Coroutine features, you must add `ktx`......

Kotlin 警告:Conditional branch result of type ... is implicity cast of Any?

具有泛型param的Kotlin抽象类和使用类型param的方法

我应该使用Kotlin数据类作为JPA实体吗?

Kotlin-将UTC转换为当地时间

项目不会使用 Kotlin 1.1.3 构建