Suspending functions are preferred over async/awai...
# coroutines
a
Suspending functions are preferred over async/await - but how do you run two suspending function concurrently?
g
Wrapping to async/launch
a
And then do await?
g
but do this on top most level
yes
a
But isn’t suspend preferred over async/await
b
suspend
is preferred for your function implementations. If inside another function, you want to use two other suspend functions concurrently, then you should use
async
for that.
Copy code
suspend fun foo(): Int { ... }
suspend fun bar(): Int { ... }

suspend fun doSomething() = coroutineScope {
    val fooAsync = async { foo() }
    val barAsync = async { bar() }
    foo.await() + bar.await()
}
3
g
As you can see from Bradyn example, even in this case you getting suspend function, do not expose any Deferred or Job. Just run 2 coroutines in parallel, await result and return doSomething result
g
as a semantic point,
foo
and
bar
are concurrent by virtue of being
suspend
. If you write the code
foo(); bar();
, then you run them sequentially, but they are still concurrent, because they do not do anything at suspension points. what you are actually looking for is "how do I run
foo
and
bar
_in parallel_". In kotlinx.coroutines, you must be explicit when you want to run things in parallel, and the typical way you do that is with
async
.
👎 1
b
Concurrent would mean that
foo()
and
bar()
are dispatched at the same time. They might not be executing in parallel (ie, a single-thread dispatcher), but they are concurrent. If you explicitly run them sequentially via
foo(); bar();
, then you would not be running them concurrently because are explicitly ensuring that
bar()
does not run until after
foo()
has completed
Parallel is concurrent. Concurrent is only sometimes parallel. Parallelism when dispatching multiple
async
coroutines depends on having enough threads for each coroutine to occupy.
3
a
Thanks! Makes sense