android - Kotlin 使用来自工作线程的协程来等待并从 UI 线程获取一些东西

标签 android multithreading kotlin kotlin-coroutines

假设您在 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/

相关文章:

Python PySide 和进度条线程

c# - 使用 BeginInvoke 动态添加 ListView 项时出现 "The calling thread must be STA, because many UI components require this."

android - Kotlin:具有关联值的枚举; 'enum entry' 内的函数得到 `unresolved reference` 错误

android - 在 Android 后台运行一个循环

android - 使用 LoaderManager 和 CursorAdapter 的 CRUD

android - 实时分享GPS位置

java - CountDownLatch 不释放线程

Android水平RecyclerView滚动方向

javascript - Javascript async 和 await 是否等同于多线程?

android - 重新安装后,Room数据库抛出错误-Room无法验证数据完整性