【问题标题】:Equivalent of observeOn and subscribeOn in Kotlin coroutines等价于 Kotlin 协程中的 observeOn 和 subscribeOn
【发布时间】:2019-02-25 07:38:33
【问题描述】:

例如:

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

通常在后台(另一个线程)执行任务并将结果返回到主线程中。

这段代码 sn-p 将如何使用 Kotlin 协程

【问题讨论】:

    标签: android kotlin kotlinx.coroutines


    【解决方案1】:

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

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

    【讨论】:

    • 单独使用backgroundTask() 代替标记的本地返回应该也可以,不是吗?
    猜你喜欢
    • 2019-10-11
    • 1970-01-01
    • 2016-10-24
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2018-06-28
    相关资源
    最近更新 更多