假设您在 WorkerThread
中执行一项长时间运行的任务。但是,为了完成上述长时间运行的任务,您必须从 UI 线程
中获取东西。
基本上,我需要访问 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
}
希望对您有所帮助。
最佳答案
你可以尝试这样的事情:
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
}
关于android - Kotlin 使用来自工作线程的协程来等待并从 UI 线程获取一些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58097968/