简体   繁体   中英

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.

My goal is to be able to call suspend functions from my non-suspend function like in the example below. Also I do not care about JS because I will use only JVM, Android, iOS targets

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.

 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.

And don't forget to use -native-mt version of coroutines if you're targeting iOS, more info here

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM