每当用户触摸屏幕时,我都试图使用AsyncTask从数据库中提取数据。每次用户触摸应用程序上的屏幕时,都会创建一个新任务。我想要的是使旧任务停止并销毁,并在用户每次触摸屏幕时都将该任务替换为新任务,而无论该任务是否已完成其工作。
这是在应用程序上下文中完成的,至少是在存储库所在的位置。 我已经做了几个控制结构,使其取消了先前的AsyncTask,但似乎没有一个起作用。
var getBoundedMomentsTask : BoundsRequestTask = BoundsRequestTask()
//Starts an asynchronous task
//Called by ViewModel
//A list of moments is returned to the live data object
fun queryMapMoments(bounds : LatLngBounds, zoom : Float ) {
//If the request is already running, end it
if (getBoundedMomentsTask.status == AsyncTask.Status.RUNNING) {
getBoundedMomentsTask.cancel(true)
}
//The while loop just hung up the system.
//while (getBoundedMomentsTask.status == AsyncTask.Status.RUNNING) {
// getBoundedMomentsTask.cancel(true)
//}
//Begin the new task
getBoundedMomentsTask.execute(BoundsTaskParams(bounds, zoom))
}
inner class BoundsRequestTask : AsyncTask<BoundsTaskParams, Void, List<Moment>>() {
override fun doInBackground(vararg params: BoundsTaskParams?): List<Moment> {
val bounds: LatLngBounds? = params[0]?.bounds
val zoom: Float? = params[0]?.zoom
if (!isCancelled) {
Log.d("doInBackground", "Getting map channel")
val channel = checkMapChannels(bounds, zoom)
if (!isCancelled) {
Log.d("doInBackground", "Asking for moments from database")
channel.fetchDatabaseMoments()
} else {
return mutableListOf()
}
if (!channel.networkRequested) {
if (!isCancelled) {
Log.d("doInBackground", "Asking for moments from network")
channel.fetchMomentsOnNetwork()
} else {
return mutableListOf()
}
}
//Save the channel and return the moments
Log.d("doInBackground", "Saving the returned channel")
channels.add(channel)
return channel.regionMoments
} else {
return mutableListOf()
}
}
override fun onPostExecute(list : List<Moment>) {
mappedMoments.value = list
}
}
我得到的错误是Cannot execute task: the task has already been executed (a task can be executed only once)
,与
getBoundedMomentsTask.execute(BoundsTaskParams(bounds, zoom))
答案 0 :(得分:1)
您必须创建一个新的AsyncTask实例。一个实例只能执行一次。