[英]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.