I have a kotlin class that takes a `suspend` funct...
# multiplatform
a
I have a kotlin class that takes a
suspend
function as a constructor parameter. How can I call this in swift? I've attempted to pass a simple closure but it complains it doesn't conform to
KotlinSuspendFunction0
. Any idea on the correct swift syntax? My attempt in 🧵.
kotlin:
Copy code
class Something(
  val myfn: suspend () -> Unit
) {}
swift: (complains
Argument type '()' does not conform to expected type 'KotlinSuspendFunction0'
)
Copy code
Something(myfn: { })
Actually I have something ugly working. Is there not a better way?
Copy code
class Hmm : KotlinSuspendFunction0 {
    func invoke() async throws -> Any? {
        print("hi?")
    }
}
Something(myfn: Hmm())
h
nope, its not
a
It's not what? Do you mean, there's not a better way?
h
Yes, there is no better way except dont using suspend functions and creating a wrapper for each call... But I prefer a swift class and use Swift 5.5 async.
a
Thanks. That sounds annoying. I've not looked at async in swift; I learnt it when it was at version 3 and haven't looked since. Hopefully it'll make the code a little nicer
h
The syntax is nice! But it also has some problems: Currently, you must call a Kotlin suspend function in the "Swift" main thread, but after calling a suspend function, the next calls are on another "Swift" thread... And Swift does not have an
runBlocking
method to call async code in non-async block. And Swift cancelation is not send to Kotlin suspend functions 😄
a
Hmm. I'm not that far into it all yet. I don't mind the suspend-function-as-a-callback thing, at least to start with. My main problem now is
MainScope()
interaction. I thought I'd got around that by simply using
suspend
methods instead. But now I'm getting the immutable coroutine exception again... Nice technology, but definitely alpha
Anyway, thanks for your replies. They were really useful
191 Views