Can someone help me understand the limitation of u...
# ios
j
Can someone help me understand the limitation of using coroutines on iOS? On https://kotlinlang.org/docs/multiplatform-mobile-concurrency-and-coroutines.html it says it "_supports usage only in a single thread. You cannot send work to other threads by changing a dispatcher_". I figured this to mean: • iOS uses one thread, so even if you switch dispatchers all coroutines will be executed on the same thread. ◦ (which shouldn't be an issue since many coroutines can run on one thread) • Performance will decrease when this thread gets blocked (because all coroutines have to wait for it to unblock) • Main thread should be safe, because from iOS you call the main
suspend
fun using async/await (and so it's not the main thread anyway) I tested this by doing a network call 20 times in a row in a suspend fun, on the IO dispatcher in my
commonMain
code:
Copy code
suspend fun run() {
  log("Starting network calls")
  repeat(20) { doNetworkCall(); log("Call $it done") }
  log("Did network calls")
}
The screen recording attached to this video shows that the UI thread doesn't get blocked. Now, please help me and correct me if I'm wrong with my two concerns about my test: 1. I see that the SwiftUI spinner keeps spinning, so I assume the main thread is not blocked; 2. This post states that the one thread is "_used for both main and background thread in iOS_", which sounds like the main thread, so it should be an issue even if my test doesn't show it? https://emmanuelkehinde.io/supporting-multithreaded-coroutines-in-a-kotlin-multiplatform-project/ (see thread for video)
iOS coroutines network calls.mov
r
Note the message at the top
This page describes the features of the legacy memory manager.
Everything on there is outdated and shouldn’t be taken as a reference for how things behave currently (unless you’re explicitly using the legacy memory manager for some reason, but you really really shouldn’t be doing that)
j
I completely missed that, @russhwolf! I think it's because the page makes references to Kotlin 1.9.0, making it feel up-to-date. But I see they need to, because you can still use the old manager today as you say. Anyway, this explains why my test code (which of course uses the new manager) runs the way it does 🙂. Thanks a lot for pointing that out! 🤗
d
I see that the SwiftUI spinner keeps spinning, so I assume the main thread is not blocked
Be aware that CoreAnimation animations don’t run on the main thread. As far as I remember, a spinner will continue spinning even if the main thread is blocked. That doesn’t mean that the main thread is blocked in your case, but just wanted to say that the spinner is not a good indicator on whether the main thread is blocked or not.