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.
The task is to be started in TextureView.SurfaceTextureListener.onSurfaceTextureAvailable
and after it finished I want to hide the progress bar. Doing this synchronously does not work because it would block the thread building the UI, leaving the screen black, not even showing the progress bar I want to hide afterwards.
So far I use this:
inner class MyTask : AsyncTask<ProgressBar, Void, ProgressBar>() {
override fun doInBackground(vararg params: ProgressBar?) : ProgressBar {
// do async
return params[0]!!
}
override fun onPostExecute(result: ProgressBar?) {
super.onPostExecute(result)
result?.visibility = View.GONE
}
}
But these classes are beyond ugly so I'd like to get rid of them.
I'd like to do this with kotlin coroutines. I've tried some variants but none of them seem to work. The one I would most likely suspect to work is this:
runBlocking {
// do async
}
progressBar.visibility = View.GONE
But this does not work properly. As I understand it, the runBlocking
does not start a new thread, as AsyncTask
would, which is what I need it to do. But using the thread
coroutine, I don't see a reasonable way to get notified when it finished. Also, I can't put progressBar.visibility = View.GONE
in a new thread either, because only the UI thread is allowed to make such operations.
I'm new to coroutines so I don't quite understand what I'm missing here.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…