Android: pass function reference to AsyncTask

后端 未结 3 537
温柔的废话
温柔的废话 2020-12-08 05:07

I\'m new to android and very used to web developing. in javascript when you want to perform an asynchronous task you pass a function as an argument (a callback):

<         


        
3条回答
  •  时光说笑
    2020-12-08 05:47

    in Kotlin

    Firstly, create class AsyncTaskHelper as below.

    class AsyncTaskHelper() : AsyncTask, Void, Boolean>() {
    
        var taskListener: AsyncListener? = null
    
        override fun doInBackground(vararg params: Callable?): Boolean {
            params.forEach {
                it?.call()
            }
            return true
        }
    
        override fun onPreExecute() {
            super.onPreExecute()
        }
    
        override fun onPostExecute(result: Boolean?) {
            super.onPostExecute(result)
            taskListener?.onFinished(result as Any)
        }
    
    }
    
    interface AsyncListener {
        fun onFinished(obj: Any)
    }
    

    the code below you can use when you want to use async task.

        AsyncTaskHelper().let {
            it.execute(Callable {
                    //this area is the process do you want to do it in background
                    // dosomething()
                    }
                }
                null
            })
            it.taskListener = object : AsyncListener{
                override fun onFinished(obj: Any) {
                    // this area is for the process will want do after finish dosomething() from Callable callback
    
    
                }
    
            }
    

    From the code above. if you want to separate your process to several task. you can do as this code below.

    AsyncTaskHelper().let {
                it.execute(Callable {
                    // task 1 do in background
                    null
                },Callable{
                    // task 2 do in background
                    null
                },Callable{
                    // task 3 do in background
                    null
                })
    
                it.taskListener = object : AsyncListener {
                    override fun onFinished(obj: Any) {
                        // when task1,task2,task3 has been finished . it will do in this area
                    }
    
                }
            }
    

提交回复
热议问题