简体   繁体   English

Kotlin 多平台:如何在没有 runBlocking 的情况下以阻塞方式启动协程

[英]Kotlin multiplatform: How to start coroutine blockingly without runBlocking

I use kotlin multiplatform which prohibits using runBlocking in common code since it is not supported by JS implementation.我使用 kotlin 多平台,它禁止在公共代码中使用 runBlocking,因为 JS 实现不支持它。

My goal is to be able to call suspend functions from my non-suspend function like in the example below.我的目标是能够从我的非挂起 function 中调用挂起函数,如下例所示。 Also I do not care about JS because I will use only JVM, Android, iOS targets我也不关心 JS,因为我只会使用 JVM、Android、iOS 目标

fun main() {
   runBlocking {
      doSomething()
   }
}

suspend fun doSomething() {
}

One solution I can think about is to create expected and actual classes and make runBlocking call separately on each platform actual class, but I want to avoid this as it will cause some code duplication.我可以考虑的一种解决方案是创建预期和实际类,并在每个平台实际 class 上分别进行 runBlocking 调用,但我想避免这种情况,因为它会导致一些代码重复。

 runBlocking {
      doSomething()
   }

Are there any better solution how to bridge blocking and non-blocking code together in common module?有没有更好的解决方案如何在公共模块中将阻塞和非阻塞代码桥接在一起?

In the common code you can use:在通用代码中,您可以使用:

CoroutineScope(Dispatchers.Default).launch {
}

or或者

MainScope().launch {
}

Depending on the scope you need.取决于您需要的 scope。

And don't forget to use -native-mt version of coroutines if you're targeting iOS, more info here如果您的目标是 iOS,请不要忘记使用-native-mt版本的协程,更多信息在这里

This won't block you current thread, as runBlocking does, so if you really need this functionality, you indeed had to implement it with expect / actual , but I have not faced a similar need.这不会像runBlocking那样阻塞你当前的线程,所以如果你真的需要这个功能,你确实必须用expect / actual来实现它,但我没有遇到类似的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Kotlin:如何在没有 runBlocking 的情况下等待非挂起的协程? - Kotlin: How to wait for a coroutine from non-suspend without runBlocking? Kotlin:协程 runBlocking 滞后 - Kotlin: lag in coroutine runBlocking Kotlin 在 runBlocking() 中取消协程 - Kotlin cancel coroutine in runBlocking() kotlin 协程 runBlocking 和 stateIn 的问题 - problem with kotlin coroutine runBlocking and stateIn 如何从另一个类(在 Kotlin 中)退出 runBlocking 协程? - How do I exit a runBlocking coroutine from another class (in Kotlin)? withTimeout 函数给出了 IllegalStateException:没有事件循环。 使用 runBlocking { ... } 启动一个。 在 Kotlin 多平台 iOS 客户端中 - withTimeout function gives IllegalStateException: There is no event loop. Use runBlocking { ... } to start one. in Kotlin Multiplatform iOS client Kotlin 协程 Scope:如果在 Controller 端点中使用,是 return@runBlocking 问题 - Kotlin Coroutine Scope : Is return@runBlocking an issue if used in Controller Endpoint 如何立即开始执行 Kotlin Coroutine - How to start executing of Kotlin Coroutine immediately 如何使用 LiveData 在 ViewModel 中启动 Kotlin 协程 - How to start Kotlin Coroutine in ViewModel with LiveData Kotlin 多平台应用程序在启动时崩溃 - Kotlin Multiplatform app crashes on start
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM