franztesca
10/13/2023, 10:34 AMasync/await
vs suspend
.
I was wondering if the main point of the comment was that suspend
is better because it's just composing a lazily evaluated function, vs async/await
being more like GlobalScope.launch { ... }.await()
, or if there is something more fundamental.
More specifically, looking at the async/await
of Swift, it seems pretty similar to suspend
(if not for ergonomics and syntax, where async/await
looks more monadic, and suspend
looks more like a co-effect), and they both enforce structured concurrency.
Does the argument of the tweet still apply for Swift, and, in that case, what is the main advantage of suspend
?
🤔CLOVIS
10/13/2023, 12:23 PMawait
(and thus memory leaks). There's no risk of forgetting to cancel the task.streetsofboston
10/13/2023, 12:53 PMasync ... await()
lines.. async--await()... async--await()...async--await() in a async function's body. Very repetitive.
There's one downside of using suspend. It's that you can't see at the call-site that it is suspend when not in the IDE (eg PR reviews). You have to go to where the function is defined to figure out it's asynchronous.franztesca
10/13/2023, 1:48 PMIMO the main advantage is that it's just a normal function call. There's no added syntax. There's no risk of forgetting to callBut that is enforced by structured concurrency, which is not necessarily bound to the syntax(and thus memory leaks). There's no risk of forgetting to cancel the task.await
suspend
(indeed Swift has structured concurrency with async/await
). You cannot forget await
and compile, the Swift compiler will stop you just like when you try to compile kotlin code that invokes a suspend function from a non-supsend context (both Swift and Kotlin rely on the compiler to prevents "illegal" things that would violate structured concurrency).
If you forget an await
in swift, your compilation fails with
error: expression is 'async' but is not marked with 'await'
To me it seems like the point is ergonomics and verbosity (you don't have to clutter your code with a redundant but very explicit await
(it's not like you can put it or not, you have to!)), is there something more fundamentally wrong with async/await
?
The same argument could be made for Arrow Raise
(Kotlin co-effect for exceptions) vs try/throws
of swift (monadic syntax of swift for exceptions, even if checked at compile time (you cannot forget)). 🤔CLOVIS
10/13/2023, 2:09 PMsuspend
, just much more verbose 😅elizarov
10/13/2023, 2:10 PMawait
, even though Swift compiler perfectly knows where it needs to be written. That is just Swift’s approach to language design. They have a similar thing with try
.