AsyncTask in Android with Kotlin

前端 未结 10 1535
离开以前
离开以前 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:10

    AsyncTask was deprecated in API level 30. To implement similar behavior we can use Kotlin concurrency utilities (coroutines).

    Create extension function on CoroutineScope:

    fun  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)
    }
    

    Now it can be used on any CoroutineScope instance, for example, in ViewModel:

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

    or in Activity/Fragment:

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

    To use viewModelScope or lifecycleScope add next line(s) to dependencies of the app's build.gradle file:

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

提交回复
热议问题