Mac*_*ich 1 multithreading android kotlin kotlin-coroutines
假设您正在WorkerThread执行一项长时间运行的任务。但是,为了完成上述长时间运行的任务,您必须从UI Thread.
基本上,我需要访问UI 线程,它将生成一个必须在 UI 线程上初始化但随后可以在任何线程中使用的对象。
我想做的是可能使用协程/挂起函数,其中工作线程实际上等待 UI 线程上的操作完成。
我怎样才能实现这样的目标?谢谢 !
以下代表了我想要实现的目标的架构:
@WorkerThread
fun processTask() {
// ... do some stuff to init work
val something = getSomethingFromUiThread() // wait
// ... resume & complete stuff with "something"
}
@MainThread
suspend fun getSomethingFromUiThread() {
// ... create object on UI Thread
// ... return initialized object to the worker thread
}
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助。
你可以尝试这样的事情:
GlobalScope.launch(Dispatchers.Main) { //Your Main UI Thread
val myuithreadobject = myobject()
withContext(Dispatchers.IO) {
//this is out background thread
nodelist = ArrayList()
val info = myuithreadobject
printAllViews(info)
}
//after background thread is finished
//do work on main thread
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4017 次 |
| 最近记录: |