Vas*_*ili 7 kotlin kotlin-coroutines
主要思想是拥有非挂起函数,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 {
val result: SomeModel = getModelResult()
launch(dispatcherFromCallerThread) { callback(result) }
}
}
data class SomeModel(val someField: String)
suspend fun getModelResult(): SomeModel {
delay(1000)
return SomeModel("TestField")
}
fun getDispatcherFromCurrentThread(): CoroutineDispatcher {
// TODO: Create dispatcher from current thread... How to do that?
}
Run Code Online (Sandbox Code Playgroud)
除非线程被设计为作为调度程序工作,否则没有一种通用的方法可以让它这样做。我想到的唯一方法是runBlocking可重入的,并将在现有线程中创建事件循环,但是它将阻止所有非协程代码在该线程上执行,直到完成。
这最终看起来像:
fun runInBackgroundAndUseInCallerThread(callback: (SomeModel) -> Unit) {
callback(runBlocking(Dispatchers.IO) {
getModelResult()
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19958 次 |
| 最近记录: |