rednifre
08/09/2022, 1:53 PMfun suspendFoo(scope: CoroutineScope): Deferred<Int> =
scope.async { 4 }
suspend fun foo(): Int {
delay(0)
return 4
}Sam
08/09/2022, 1:55 PMscope could still affect how the async job gets dispatched for examplerednifre
08/09/2022, 1:57 PMrednifre
08/09/2022, 1:58 PMSam
08/09/2022, 2:00 PMfun suspendFoo(cont: Continuation<Int>) {
cont.resumeWith(4)
}
The library decides how to implement Continuation (which is an interface)Sam
08/09/2022, 2:03 PMSam
08/09/2022, 2:07 PMrunCatching { foo() }
then no errors can escape from that function, but if you write
runCatching { suspendFoo(scope).await() }
then it can and will still propagate exceptions to the scope.rednifre
08/09/2022, 2:12 PMSam
08/09/2022, 2:12 PMasync will launch the job in the background whereas calling a suspend function runs in the foreground. Your example is probably simple enough that both versions will complete immediately anyway, though I don’t know if that’s guaranteed.Sam
08/09/2022, 2:14 PMsequence { ... } — because it’s based on suspend functions and continuations but is unrelated to (and much simpler than) the kotlinx.coroutines libraryrednifre
08/09/2022, 2:16 PMRick Clephas
08/09/2022, 4:33 PMrunCatching { foo() }
runCatching { suspendFoo(scope).await() }
If I am not mistaken both of these wil be the same in terms of the returned result.
await will throw the exception similar to how calling a regular suspend function would.
The main difference would be in immediately waiting the result or not.
When using the Deferred approach you can execute some other work before awaiting the result.
E.g the following will only for 2 seconds (since both delays are running at the same time.
val deferredDelay = async { delay(2_000) }
delay(1_000)
deferredDelay.await()
While the following would result in a 3 second delay (since the second is only started after the first completes).
delay(2_000)
delay(1_000)
Note that async doesn’t guarantee immediate execute. Instead the job is dispatched.
If you need immediate execution you can pass CoroutineStart.UNDISPATCHED to the start parameter:
https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-start/Sam
08/09/2022, 4:40 PMscope.async will attempt to cancel its parent when it fails, same as scope.launch. It's caught me out a few times.Rick Clephas
08/09/2022, 5:03 PMJob that would indeed affect other jobs inside the scope (SupervisorJob can be used if that isn’t the desired behaviour).
But if that is desired or not will likely depend on where the scope is coming from.
E.g. in case of coroutineScope that would be perfectly valid: https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html