小编Vas*_*ili的帖子

Kotlin 协程 - 如何在后台运行并在调用者线程中使用结果?

主要思想是拥有非挂起函数,runInBackgroundAndUseInCallerThread(callback: (SomeModel) -> Unit)该函数在后台(另一个线程)异步运行一些工作,并在工作完成后 - 在调用者线程(启动的线程runInBackgroundAndUseInCallerThread)中运行回调。

下面我写了一个示例代码,但我不确定它的正确性以及是否可行。我用println("1/2/3/...")标记了所需的呼叫顺序。 getDispatcherFromCurrentThread- 如果可以实现这个功能,那么可以使用解决方案,但我不知道如何实现它,这样做是否正确。

因此,请不要将其视为唯一的解决方案。

import kotlinx.coroutines.*
import kotlin.concurrent.thread

fun main() {
    println("1")
    runInBackgroundAndUseInCallerThread {
        println("4")
        println("Hello ${it.someField} from ${Thread.currentThread().name}") // should be "Hello TestField from main"
    }
    println("2")
    thread(name = "Second thread") {
        runInBackgroundAndUseInCallerThread {
            println("5")
            println("Hello ${it.someField} from ${Thread.currentThread().name}") // should be "Hello TestField from Second thread"
        }
    }
    println("3")
    Thread.sleep(3000)
    println("6")
}

fun runInBackgroundAndUseInCallerThread(callback: (SomeModel) -> Unit) {
    val dispatcherFromCallerThread: CoroutineDispatcher = getDispatcherFromCurrentThread()
    CoroutineScope(Dispatchers.IO).launch { …
Run Code Online (Sandbox Code Playgroud)

kotlin kotlin-coroutines

7
推荐指数
1
解决办法
2万
查看次数

标签 统计

kotlin ×1

kotlin-coroutines ×1