4

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?

1
  • 可以暂时使用 run-blocking-kmp.javiersc.com, 然后等待官方支持 Commented Oct 13 at 2:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.