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