I’m having a problem implementing a kotlin `suspen...
# multiplatform
m
I’m having a problem implementing a kotlin
suspend
function in Swift I have an interface, e.g.:
Copy code
interface Loader {
    suspend fun fetch()
}
which I implement in Android and in iOS. The iOS version looks like this:
Copy code
public class RemoteFeatureLoader : Loader {
    public func fetch(completionHandler: @escaping (KotlinUnit?, Error?) -> Void) {
        
        doAsyncStuff { [weak self] in
            completionHandler(KotlinUnit(), nil)
        }
    }
}
And the caller in the shared code looks like this
Copy code
class CommonLoader() {
    override suspend fun fetch() {
        localFeatureLoader.fetch()
        remoteFeatureLoader.fetch()
    }
}
and finally, the
CommonLoader.fetch()
is being called from a view model which is also shared
Copy code
class CommonViewModel(
    private val scope: CoroutineScope,
    private val uiContext: CoroutineContext,
) : ViewModel {

    override fun startup() {
        scope.launch(context = uiContext) {
            loader.fetch()
        }
    }
}
Basically, the Android version works like a charm, but the iOS version hangs at
loader.fetch()
If I add a log after
remoteFeatureLoader.fetch()
it is printed just fine, but the function never returns/resumes from its suspended state. Does anyone have any clue what could be going on? I appreciate any help! Thank you!
a
Also curious about this. We currently declare any
interface
intended to be implemented outside of Kotlin with a callback-based API. This lets us pretty easily implement them in Swift. We then convert the callbacks to `suspend fun`s within our KMP codebase, so we can use coroutines within Kotlin.
m
This is the suggested approach given by my teammate as well Implementing my interface in Swift gave me two options:
Copy code
public func fetch() async throws -> KotlinUnit
and
Copy code
public func fetch(completionHandler: @escaping (KotlinUnit?, Error?) -> Void)
I couldn’t try the first one as it is only for iOS 15 at the moment, but the second one should theoretically work
a
Yeah... I think the
suspend fun
->
completionHandler
mapping is only be unidirectional (Kotlin -> Swift) and may not be supported in the opposite direction
m
@Matheus Finatti Hi, I am also developing KMM suspend fun. I too decided to use callbacks instead of coroutines since swift doesn’t support coroutines for now. can you please let me know how u have done callbacks in ios (KMM) ? @ankushg / @Matheus Finatti please share any gitHub or reference code base if you came across, waiting for you guys response, Thanks !!