android - Kotlin 协程中 observeOn 和 subscribeOn 的等价物

标签 android kotlin kotlinx.coroutines

例如:

Observable.fromCallable<Int> {
   backgroundTask() // returns an integer
   }
   .observeOn(AndroidSchedulers.mainThread())
   .subscribeOn(Schedulers.io())
   .subscribe ({ number -> /* success */ }, { error -> /* fail */ })

通常 在后台(另一个线程)执行任务并在主线程中获取它的结果。

此代码 fragment 将如何使用 Kotlin 协程

最佳答案

您可以使用 withContext() 切换线程。例如,

launch(Dispatchers.MAIN) {
    //main thread here
    val result = withContext(Dispatchers.IO) {
        //IO thread here
        backgroundTask()
    }
    //main thread here again
    //doing something with result
}

关于android - Kotlin 协程中 observeOn 和 subscribeOn 的等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54861493/

相关文章:

android - Jetpack Compose 中的长按手势

Kotlin 协程 : concurrent execution throttling

java - 使用 Volley 时后台服务出现 OutofMemory 错误

android - 通过 ADB 安装新的启动器应用程序时,未清除家庭默认应用程序

android - 如何在原生 android 2019 中使用 WebRTC

android - Kotlin fragment

kotlin - 迁移到非实验性协程

kotlin - 没有 ReactiveCrudRepository 的 WebFlux 和 Kotlin 协程

Android 测试 - 信号质量

android - 如何自动缩放 OpenGL ES 2.0 窗口?