How can we run Kotlin Coroutines from iOS? did some research and found couple of things. this <https...
h
How can we run Kotlin Coroutines from iOS? did some research and found couple of things. this https://touchlab.co/kotlin-coroutines-rxswift/ article is talking about creating a wrapper and using it for every suspend and flow function. This https://medium.com/futuremind/handling-kotlin-multiplatform-coroutines-in-swift-koru-4a80b93f232b article is pointing out that first article is correct but you have manually create boilerplate code. you can use this https://github.com/FutureMind/koru library to generate boilerplate automatically. Also official docs from Kotlin https://kotlinlang.org/docs/native-ios-integration.html and some other library https://github.com/rickclephas/KMP-NativeCoroutines and article about using Swift async/await for suspend https://johnoreilly.dev/posts/swift_async_await_kotlin_coroutines/ is there another library or should I use one of these or is there a way to do this without libraries and boilerplate?
a
We have been using KMP-NativeCoroutines and overall been very happy with it. With the later versions (still ALPHA I believe) there is 0 boiler plate in the Swift code.
It is getting reduced more and more and I believe the biggest issue now is the limitations on the dispatchers in other systems (in SwiftUI for example, the coroutine runs on the main thread). With KMM-ViewModel, one of the key things the view model does is makes sure the coroutines run on the appropriate context in Android / Apple
h
is there a way to keep coroutine stuff in common module and not bother at all about running it in iOS?
t
yes, you can use some kind of Class that transfers the state of your Flows and such using non-coroutine methods (e.g. a simple listener and setter) which you then wrap using whatever iOS method you use to observe nativly (e.g. Combine). We still use this approach at my work, because we’ve been doing that since before
StateFlow
and
SharedFlow
even existed and it actually works pretty well (and also allows observing things that are not a Flow). But if your entire viewmodel is a bunch of (State)Flows I’d consider the more direct approaches as outlined above though. for what it’s worth we also opensourced what we use internally: https://github.com/splendo/kaluga/tree/develop/architecture#observables-and-subjects
p
There’s also this option to map Flows to Combine which I ended up using in one of my projects. The KMP-NativeCoroutines plugin didn’t suit my needs because I had a similar parameterized interface like you described here https://kotlinlang.slack.com/archives/C3PQML5NU/p1681543745203519
h
@Pavel S thank you very much will try this one