this may be a dumb question, but I created a KN cl...
# kotlin-native
t
this may be a dumb question, but I created a KN class that has 2 functions: one is a regular
fun
and the other one is a
suspend fun
, which is using coroutines to make a network call. on android, i can see both functions from this class. i can call them, and life is good. on ios, I can only see the function that is a regular
fun
. the
suspend fun
is not visible at all. what did i miss? does iOS not support suspending functions from coroutines?
y
suspend fun
is not exported to
.framework
on iOS at this time.
t
😞
y
in common, define suspend fun
t
is there an alternative for this?
y
in actual, use it in coroutine
for example
j
you may understand the
suspend
function as a function with callback, that is executed when function is completed. You cannot call such function from Java, and objc. The workaround is wrap the coroutine with an ordinary function. https://github.com/Kotlin/kotlinx.coroutines/issues/470#issuecomment-440080970 That may help
t
oh. ok @yuya_horita, I can do that for android. what do you for iOS in the KN code?
y
yes, thank you @ jonnyzzz
I defined function like below in common module
Copy code
suspend fun hello(): String {
        try {
            return helloRepository.hello()
        } catch (e: Throwable) {
            throw e
        }
}
and, did in actual ios module
Copy code
fun HelloService.sendHello(block: (String?, Error?) -> Unit) {
    launch(block) {
        this@sendHello.hello()
    }
}
I use this actual function from swift code.
t
ok. thanks
y
be careful using correct
CoroutineDispathcer
Copy code
internal class MainScope: CoroutineScope {
    private val context = MainDispatcher()
    private val job = Job()
    private val exceptionHandler = CoroutineExceptionHandler { _, _ -> }

    override val coroutineContext: CoroutineContext
        get() = context + job + exceptionHandler
}

private class MainDispatcher: CoroutineDispatcher() {
    override fun dispatch(context: CoroutineContext, block: Runnable) {
        dispatch_async(dispatch_get_main_queue()) { block.run() }
    }
}
this will help you
t
who's calling that last chunk of code?
y
sorry, which code?
MainScope?
t
yes
MainScope and MainDispatcher
y
MainDispatcher is used just for MainScope
and
Copy code
internal fun <T> launch(block: (T?, Error?) -> Unit, suspendBlock: suspend CoroutineScope.() -> T) {
    MainScope().launch {
        try {
            val response = suspendBlock()
            block(response, null)
        } catch (e: Error) {
            block(null, e)
        }
    }
}
t
but is it used by common? jvm? kotlin android app?
y
in common, suspend function is defined, so there is no problem for kotlin android app.
this is used by ios app
t
what does iOS call?
y
above
sendHello
function
like
Copy code
in Swift
Services.helloService.sendHello {  response, error in
        }
sendHello is just a wrapper for
hello()
suspend function.
t
ok. cool. thanks!
y
yes!