本文介绍了AsyncTask作为Kotlin协程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AsyncTask的典型用法:我想在另一个线程中运行一个任务,完成该任务后,我想在我的UI线程中执行一些操作,即隐藏进度条.

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.

该任务将在TextureView.SurfaceTextureListener.onSurfaceTextureAvailable中启动,完成后,我想隐藏进度条.同步执行此操作不起作用,因为它将阻止构建UI的线程,使屏幕变黑,甚至不显示我随后要隐藏的进度条.

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

但是这些类太丑陋了,所以我想摆脱它们.我想用Kotlin协程来做到这一点.我已经尝试了一些变体,但它们似乎都不起作用.我最有可能怀疑的工作方式是:

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

但是这不能正常工作.据我了解,runBlocking不会像AsyncTask那样启动新线程,这是我需要它执行的操作.但是,使用thread协程,我看不到在完成时获得通知的合理方法.另外,我也不能将progressBar.visibility = View.GONE放入新线程中,因为仅允许UI线程进行此类操作.

But this does not work properly. As I understand it, the runBlockingdoes 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.

我对协程真的很陌生,所以我不太了解我在这里缺少什么.

Im really new to coroutines so I don't quite understand what I'm missing here.

推荐答案

首先,您必须使用launch(context)而不是runBlocking运行协程: https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html

First, you have to run coroutine with launch(context), not with runBlocking:https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html

第二,要获得onPostExecute的效果,您必须使用

Second, to get the effect of onPostExecute, you have to use

Activity.runOnUiThread(Runnable) View.post(Runnable).

这篇关于AsyncTask作为Kotlin协程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 07:58