Android 中的 AsyncTask 与 Kotlin

新手上路,请多包涵

如何使用 Kotlin 在 Android 中进行 API 调用?

我听说过 安科。但我想使用 Kotlin 提供的方法,比如在 Android 中我们有 Asynctask 用于后台操作。

原文由 Rakesh Gujari 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 922
2 个回答

AsyncTask 是一个 Android API ,不是 Java 或 Kotlin 提供的 语言功能。如果你愿意,你可以像这样使用它们:

 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 的 doAsync 并不是 Kotlin 真正“提供”的,因为 Anko 是一个使用 Kotlin 的语言特性来简化长代码的库。在这里检查:

如果您使用 Anko,您的代码将类似于:

 doAsync {
    // ...
}

原文由 shiftpsh 发布,翻译遵循 CC BY-SA 3.0 许可协议

AsyncTask 在 API 级别 30 中已弃用。为了实现类似的行为,我们可以使用 Kotlin 并发实用程序(协程)

CoroutineScope 上创建扩展函数:

 fun <R> CoroutineScope.executeAsyncTask(
        onPreExecute: () -> Unit,
        doInBackground: () -> R,
        onPostExecute: (R) -> Unit
) = launch {
    onPreExecute()
    val result = withContext(Dispatchers.IO) { // runs in background thread without blocking the Main Thread
        doInBackground()
    }
    onPostExecute(result)
}

现在它可以用于任何 CoroutineScope 实例,例如,在 ViewModel 中:

 class MyViewModel : ViewModel() {

      fun someFun() {
          viewModelScope.executeAsyncTask(onPreExecute = {
              // ...
          }, doInBackground = {
              // ...
              "Result" // send data to "onPostExecute"
          }, onPostExecute = {
              // ... here "it" is a data returned from "doInBackground"
          })
      }
  }

或在 Activity / Fragment

 lifecycleScope.executeAsyncTask(onPreExecute = {
      // ...
  }, doInBackground = {
      // ...
      "Result" // send data to "onPostExecute"
  }, onPostExecute = {
      // ... here "it" is a data returned from "doInBackground"
  })

要使用 viewModelScopelifecycleScope 将下一行添加到应用程序的 build.gradle 文件的依赖项中:

 implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$LIFECYCLE_VERSION" // for viewModelScope
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$LIFECYCLE_VERSION" // for lifecycleScope

原文由 Sergio 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题