使用Coroutine进行连续数据轮询并将其倾倒到UI
我现有的Android代码使用asynctask
从虚拟com 端口连续进行轮询数据,并通过覆盖onprogressupdate()
函数来将数据转移到UI线程中。如下:
open class ComActivity(deviceID:Int, listener: OnComRxUpdateUI) : AsyncTask<..., ..., ...>(){
...
override fun doInBackground(...) {
... //keep listening on serial port and transfer byte to buffer when available
}
override fun onProgressUpdate(...){
... //dump to ui
}
}
上面的代码正常工作(除了在此处和那里进行一些内存泄漏警告外)。
时不时地,我看到coroutine
被促进以执行并发和异步操作,并且发现被迫尝试用coroutine替换asynctask
。 OTOH,我没有完全掌握coroutines
的工作,以替代asynctask
。因此,我的问题是coroutine
是否是可行的更换我的用例(连续数据轮询和在UI上倾倒)。任何优秀的高级(或伪)例子 欢迎在那里证明这种用例。
My existing Android code uses AsyncTask
to continuously poll data from a virtual COM port and dumps data to UI thread by overriding the onProgressUpdate()
function. Something like the following:
open class ComActivity(deviceID:Int, listener: OnComRxUpdateUI) : AsyncTask<..., ..., ...>(){
...
override fun doInBackground(...) {
... //keep listening on serial port and transfer byte to buffer when available
}
override fun onProgressUpdate(...){
... //dump to ui
}
}
The above code works fine (except for some memory leak warnings here and there).
Every now and then, I see Coroutine
being promoted for performing concurrent, and asynchronous operations, and I find compelled to try replacing AsyncTask
with Coroutine. OTOH, I do not fully grasp the working of Coroutines
as a substitute for AsyncTask
. So my question is whether Coroutine
is a viable replacement for my use case (continuous data polling and dumping on UI). Any good high-level (or pseudo) example
out there that demonstrate this use case are welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很难假设您在
asynctask
的串行端口上的收听方式,无论您是使用某种侦听器还是无限循环,但是我想使用flow
和mvvm
方法。它的外观如下:在存储库类中:
在
viewModel
中:states:
in UI(
activity
或fragment
):如果您不是是使用
mvvm
体系结构的方法的粉丝,您可以在UI类中完成所有操作(活动
或fragment
),我我不喜欢t建议:It is hard to assume how you are listening on a serial port in
AsyncTask
, whether you use some kind of listener or an infinite loop, but I guess the same result can be achieved usingFlow
andMVVM
approach. It will look something like the following:In Repository class:
In
ViewModel
:States:
In Ui(
Activity
orFragment
):If you are not a fan of the approach of using
MVVM
architecture, you can do all of it in UI class(Activity
orFragment
), which I don't recommend: