The suspend functions as converted by SKIE require...
# touchlab-tools
m
The suspend functions as converted by SKIE require
try
on swift side even if the original functions do not have
@Throws
annotation. I am wondering if this is by design or some limitation or maybe due to cancellation?
f
Yes, it’s because of cancellation support. Coroutines functions signal cancellation by throwing the CancellationException which needs to be propagated to the Swift side.
gratitude thank you 1
m
I still cannot 100% wrap my head around how that works and why it's necessary, tbh. E.g. should I
Copy code
try! await myNonThrowingSuspendFunction.invoke()
because it will never throw? Or will it throw and crash upon cancellation of the swift Task and thus the wrapped coroutine? And therefore I should rather gracefully handle some kind of an error?
f
yes, it will crash the app when the task and therefore the call is cancelled. You need to handle the Cancellation exception in an appropriate way - depending on the context and the kind of function. When cancellation happens the execution flow has to somehow return to the root of the task/coroutine - both in Kotlin and Swift. In Kotlin this is handled by the CancellationException and exception propagation. In Swift there are multiple options. The cancelled function can throw a similar exception and propagate it like in Kotlin. Except, in Swift this has to be handled by the developer because Swift doesn’t have implicit exception propagation. Another option is for the function call to return null, 0 or other default value which signals the cancellation to the caller (then it’s up to the called to react and handle the cancellation in some way, etc.). Or if the function does not return a value, it can just stop and return prematurely. This is how for example for loops over async sequences work - they just stop the iteration and the execution continues right past them. So in summary, in most cases you can use
try
and let the exception propagate to the Task root, or sometimes also
try?
if you are ok with the cancellation being represented as no-op or
nil
. Rarely you would do
do catch
with some other handling. As for
try!
- you can use it only if you are 100 % sure the code cannot be cancelled (from both Kotlin and Swift). That doesn’t mean I would recommend to use that even in that case. It can always cause problems somewhen later when the code changes without respecting this rule
❤️ 1
m
Excellent explanation, thank you!