hi .. when calling shared kotlin suspend functions...
# multiplatform
v
hi .. when calling shared kotlin suspend functions from swift code, we get a completion block with data and error... and i didn't see any situation in which the error would be NOT NIL. can anyone please explain when will i get the error?
m
If you have the function annotated with a
@Throws
it can contain that. Otherwise it will only be the CancelationException. I’m not sure how that would trigger, since it doesn’t seem like there is anything that could cancel it. Only thing I can thing of is awaiting on an async from another scope and that scope was canceled or the async itself was canceled.
v
https://play.kotlinlang.org/hands-on/Networking%20and%20Data%20Storage%20with%20Kotlin%20Multiplatfrom%20Mobile/07_Building_SDK in this the suspend function getAllLaunches is annotated with
@Throws
but what is the use of this annotation here...?
m
It tells Kotlin that an exception can be thrown and that the should pass it nicely to Java and Objective-C instead of crashing. Although throwing Exception is lazy.
But too many Kotlin libraries don’t advertise what they might throw so you’re stuck trying to handle everything. KTOR being one of those libraries. Just because Kotlin doesn’t have checked exceptions doesn’t mean libraries shouldn’t document what exceptions you should be handling.
r
Like @mkrussel mentioned only exception classes defined in the
@Throws
annotation are passed to ObjC/Swift. Any other exception will terminate the program. This behaviour is explained in more detail in the docs. Without the
@Throws
annotation you’ll likely never receive an error since you can’t cancel the suspend function from Swift. Though you will receive `CancelationException`s thrown by e.g.
withTimeout
. FYI if you want more control over your suspend functions you should instead use some kind of wrapper function that exposes an option to cancel the function. Or use a library that does this for you. Like the one I developed: https://github.com/rickclephas/KMP-NativeCoroutines