Kotlin IO线程分派完成时在主线程中运行代码?

Kotlin IO线程分派完成时在主线程中运行代码?,kotlin,kotlin-android-extensions,mutablelivedata,Kotlin,Kotlin Android Extensions,Mutablelivedata,我正在使用livedata。我想在IO中运行一些任意代码,完成后,在主线程中运行一些任意代码 在JavaScript中,您可以通过将承诺链接在一起来完成类似的事情。我知道Kotlin是不同的,但这至少是我理解的一个框架 我有一个函数,有时从Main调用,有时从IO调用,但它本身不需要特殊的IO功能。从类VM中:ViewModel(): 可以在ViewModel中运行吗 请在上述适当的情况下,将“线程”替换为“协同路由”: 发射很好。您只需切换dispatchers并将与上下文一起使用即可: fu

我正在使用livedata。我想在IO中运行一些任意代码,完成后,在主线程中运行一些任意代码

在JavaScript中,您可以通过将承诺链接在一起来完成类似的事情。我知道Kotlin是不同的,但这至少是我理解的一个框架

我有一个函数,有时从Main调用,有时从IO调用,但它本身不需要特殊的IO功能。从
类VM中:ViewModel()

可以在ViewModel中运行吗


请在上述适当的情况下,将“线程”替换为“协同路由”:

发射很好。您只需切换dispatchers并将
与上下文一起使用即可:

fun getValFromDb() {
    // run this coroutine on main thread
    viewModelScope.launch(Dispatchers.Main) {
        // obtain result by running given block on IO thread
        // suspends coroutine until it's ready (without blocking the main thread)
        val a: MyVal = withContext(Dispatchers.IO){ fetchFromDb() }
        // executed on main thread
        setVal(a) 
    }
}

发射很好。您只需切换dispatchers并将
与上下文一起使用即可:

fun getValFromDb() {
    // run this coroutine on main thread
    viewModelScope.launch(Dispatchers.Main) {
        // obtain result by running given block on IO thread
        // suspends coroutine until it's ready (without blocking the main thread)
        val a: MyVal = withContext(Dispatchers.IO){ fetchFromDb() }
        // executed on main thread
        setVal(a) 
    }
}

似乎是
runBlocking
async
的某种组合,而不是
launch
maybe?似乎是
runBlocking
async
的某种组合,而不是
launch
maybe?无需明确指定
Dispatchers.Main
,这是
viewModelScope
的隐式分派器。无需明确指定
Dispatchers.Main,即
viewModelScope
的隐式dispatcher,请参阅文档。见
fun getValFromDb() {
    // run this coroutine on main thread
    viewModelScope.launch(Dispatchers.Main) {
        // obtain result by running given block on IO thread
        // suspends coroutine until it's ready (without blocking the main thread)
        val a: MyVal = withContext(Dispatchers.IO){ fetchFromDb() }
        // executed on main thread
        setVal(a) 
    }
}