Has anyone used `kotlinx.coroutines.runBlocking` o...
# kotlin-native
b
Has anyone used
kotlinx.coroutines.runBlocking
on iOS? https://github.com/bootstraponline/run_blocking/blob/master/src/commonMain/kotlin/example/Common.kt https://github.com/bootstraponline/run_blocking/blob/master/src/iosMain/kotlin/example/RunBlocking.kt I have a simple example that compiles to an iOS framework. iOS hangs on
kotlinx.coroutines.runBlocking
and never returns. On the JVM, runBlocking works as expected.
r
It can be made to work. Can you show more specifically where it’s failing for you? From a glance at your repo I don’t even see where you’re running iOS tests.
b
message has been deleted
message has been deleted
The repo only produces a framework, there's no iOS test. I'm dragging & dropping the framework into an iOS app and then invoking the method. The
healthCheck
method is defined in
Common.kt
linked above.
r
Hm. I’m guessing the issue is that the default dispatcher on iOS is single-threaded and that’s causing something to hang. A common pattern is to expect/actual a
mainDispatcher
which is
Dispatchers.Main
on Android and a custom dispatcher on iOS. That custom dispatcher then can look something like this https://github.com/russhwolf/multiplatform-hello/blob/master/shared-client/src/iosMain/kotlin/mainDispatcher.kt
You also might find that repo useful for some other testing patterns. You can configure an
iosTest
gradle task that runs tests on the simulator without needing to involve xcode. And you can pass a mock engine to ktor so you don’t need to make an actual web call in your tests.
b
That's awesome. Thanks for the info! I'm hoping some of the announcements from Kotlinconf means this will work out of the box one day.
r
Yeah it’s moving along but we’re not all the way there yet
b
This scenario should work fine I think. The one thing I noticed is that the runBlocking lambda definitions aren't quite right. They should be
runBlocking(block: suspend CoroutineScope.() -> T): T
The "CoroutineScope." part might be important for it to work properly, but I'm not exactly sure why
r
If you don’t need to launch any child coroutines, I don’t think the scope should matter. Ultimately it’s just an input parameter to the lambda which in this case isn’t used.
b
Right but runBlocking will loop until all async work inside it is done. Speculating that CorutineScope has something to do with it but not sure what
Now I want to debug this tomorrow, but I prob don't have time 😓