AsyncTask as kotlin coroutine

后端 未结 5 487
长发绾君心
长发绾君心 2020-12-06 02:50

Typical use for AsyncTask: I want to run a task in another thread and after that task is done, I want to perform some operation in my UI thread, namely hiding a progress bar

5条回答
  •  没有蜡笔的小新
    2020-12-06 03:21

    Another approach is to create generic 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 we can use it with any CoroutineScope:

    • 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"
                })
            }
        }
      
    • In Activity or 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
    

    At the time of writing final LIFECYCLE_VERSION = "2.3.0-alpha05".

提交回复
热议问题