Issue
I am trying to use an AsyncTask to pull data from a database whenever a user touches the screen. A new task is created every time the user touches the screen on the app. What I want is for the old task to be stopped and destroyed and replaced with a new task each time the user touches the screen whether or not that task has finished its work.
This is done in application context, at least that is where the Repository is. I've made several control structures to make it cancel the prior AsyncTask but none seem to work.
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
}
}
The error I get is Cannot execute task: the task has already been executed (a task can be executed only once)
on the line with
getBoundedMomentsTask.execute(BoundsTaskParams(bounds, zoom))
Solution
You have to create a new instance of thee AsyncTask. A single instance can only be executed once.
Answered By - Gabe Sechan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.