Is there a way to have a callback in Kotlin/Native...
# kotlin-native
p
Is there a way to have a callback in Kotlin/Native?
Copy code
private suspend fun syncFromNewtork(url: String): Boolean = suspendCoroutine { continuation ->
    val knResponseCallback: KNSyncManagerResponseCallBack = freezeObject(KNSyncManagerResponseCallBack(continuation))

    knNetworkBridge.makePostRestRequest(url: url)
}

class KNSyncManagerResponseCallBack(private val continuation: Continuation<Boolean>): KNResponseCallback {
    override fun onSuccess(response: Any?) {
        continuation.resume(true)
    }

    override fun onError(errorResponse: Any?) {
        continuation.resume(false)
    }
}
In this case, the KN side will call iOS side via network bridge and iOS side will make the actual network call on a different thread. It will then give a callback on a diff thread and KN has to handle it. Continuation has to be mutable and at the same time accessible between threads. How do I handle this? Is this a good practice? Will I have to use AtomicRefs here?
k
you'll either need atmoics or you will need to transfer ownership of the object between threads
b
p
Thanks Ben and Kris. Tried it with atomics itself. Makes it a bit dirty but I do not think there is any other way.
b
tl;dr to avoid freezing the continuation, you wait and delay in the current thread/coroutine for the result to be posted from your bg thread into an atomic var
👍 1
p
I am actually calling the ios swift function from the coroutine. waiting the coroutine would mean trying to make the swift function synchronous (network call) and would require me to do some semaphore or other synchronization construct. Also, that implementation wouldnt be compatible with Android.
I mean it would be compatible but Android does not have that problem but still it will have to do something like iOS which is inefficient. Ami I rright?
b
In the library on android, the implementation is different and avoids doing all this because it's not needed
p
ohh ok..will have a look at it
b
It's not synchronous because the delay suspends
It's the best that can be done for this scenario without the improved support for coroutines on native, which is coming in a future coroutines release
p
Got it. Thanks
👍 1
t
tl;dr to avoid freezing the continuation, you wait and delay in the current thread/coroutine for the result to be posted from your bg thread into an atomic var
Hi @basher, thanks for the solution, it really helped me! Do you know if this is still the best way to prevent freezing because of all the changes in
native-mt
?
b
I believe that in native-mt, you don't have to take the same precautions around freezing coroutine internals. I haven't spent much time with native-mt yet, but I expect you could then switch to whatever the idiomatic method is in coroutines generally
t
Yes you’re right! I just tried
suspendCancellableCoroutine
with native-mt and the continuation appears to already be frozen (at least in my testing code)
🎉 1