gpt4 book ai didi

android - Rxjava 与 kotlin 协程

转载 作者:行者123 更新时间:2023-11-29 22:59:16 27 4
gpt4 key购买 nike

我需要从 rxkotlin 链启动协程,但我不确定这是对还是错,要从 rx 链启动协程,我使用 runblocking 启动挂起方法
示例

Single.just(someOperation())
.map{
someMethod(it)
}
.flatMap{
startCoroutines(suspend { someOpeartions() } ) // i will be starting the coroutines here
}

协程

fun startCoroutines(suspendingObj : suspend () -> Any){
runBlocking(newFixedThreadPoolContext(1,"Thread")){
suspendingObj.invoke()
}
}

上面的代码是正确的做法还是有其他方法可以实现?谁能帮我解决这个问题

最佳答案

这个代码块从根本上是错误的。

  1. 在您的情况下,确实没有必要使用协程,因为您可以使用 observeOnflatMap 之前轻松更改 Rx 线程,并传递任何 Scheduler 你想要(比如 IO)。
  2. Kotlin 协程旨在避免Threads,因为创建Threads 是一项非常昂贵的操作。并且您的函数 startCoroutines 为每个操作创建一个新线程,这没有任何意义并且可能会导致 溢出。您可以在这里阅读更多相关信息:Difference between a "coroutine" and a "thread"?
  3. 在决定使用 runBlocking 之前,您应该始终尝试找到更好的系统设计。阻塞线程从来都不是一个好主意。

关于android - Rxjava 与 kotlin 协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57105778/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com