https://kotlinlang.org logo
m

Martin Rajniak

03/11/2022, 3:42 PM
Do you folks use KMP code from native (iOS) background threads? I have an existing iOS project and would like to replace single platform solution in it with KMP library. Currently iOS project is calling the solution from the background thread. Naively I thought I will just replace one callback method with another (generated from
suspend
function). But this is not possible if I understand correctly:
Calling Kotlin suspend functions from Swift/Objective-C is currently supported only on main thread
I am using Kotlin 1.6.10, Coroutines 1.6.0 (without
native-mt
) and new experimental memory model. Is the current practice to leave threading to multi-platform code or am I missing something?
r

russhwolf

03/11/2022, 4:53 PM
If you write your own callback wrapper rather than using the built-in one, then you can handle your own threading
m

Martin Rajniak

03/11/2022, 5:12 PM
Thanks, will give it a try. Any good examples?
m

Mike Wolfson

03/11/2022, 6:38 PM
subscribed (definitely need this same thing)
h

hfhbd

03/11/2022, 7:46 PM
r

Rick Clephas

03/16/2022, 7:50 AM
Any good examples?
That would depend on your needs. You could define a fairly simple wrapper that does the same as the default completion handler version, or you can write a wrapper that fully supports coroutines (with cancellation). I actually created a library for the full support version: https://github.com/rickclephas/KMP-NativeCoroutines. With the following Kotlin wrapper for suspend functions: https://github.com/rickclephas/KMP-NativeCoroutines/blob/9a9a18086f093126a218057b3434b8ceafef2e2f/kmp-nativecoroutines-core/src/nativeCoroutinesMain/kotlin/com/rickclephas/kmp/nativecoroutines/NativeSuspend.kt
🙏 1
m

Martin Rajniak

03/16/2022, 7:55 AM
Btw, do you know how to create wrapper that does the same as default completion handler ? It generates NSError and I was not able to do that myself. JVM Throws generated throws in Swift as well. And passing Kotlin Exception creates Kotlin Exception object on the other side.
r

Rick Clephas

03/16/2022, 8:00 AM
Yeah you can get pretty close to the default implementation. To get the same structured NSError you can do something like this: https://github.com/rickclephas/KMP-NativeCoroutines/blob/9a9a18086f093126a218057b3434b8ceafef2e2f/kmp-nativecoroutines-core/src/appleMain/kotlin/com/rickclephas/kmp/nativecoroutines/NativeErrorApple.kt Though this isn’t fully compatible in the sense that Kotlin won’t convert it back to an
Exception
if it somehow reaches Kotlin again (it will just wrap it into an exception instead). There are some technical limitations that prevent the interop logic from being used in app/library code: https://youtrack.jetbrains.com/issue/KT-50539 I do however have a POC that exposes this logic: https://github.com/rickclephas/NSErrorKt
m

Martin Rajniak

03/16/2022, 8:02 AM
Nice thank you :)
96 Views