https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

asad.awadia

01/31/2019, 2:45 AM
Suspending functions are preferred over async/await - but how do you run two suspending function concurrently?
g

gildor

01/31/2019, 2:49 AM
Wrapping to async/launch
a

asad.awadia

01/31/2019, 2:49 AM
And then do await?
g

gildor

01/31/2019, 2:49 AM
but do this on top most level
yes
a

asad.awadia

01/31/2019, 2:50 AM
But isn’t suspend preferred over async/await
b

bdawg.io

01/31/2019, 2:53 AM
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

gildor

01/31/2019, 3:02 AM
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

groostav

01/31/2019, 3:04 AM
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

bdawg.io

01/31/2019, 3:17 AM
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

asad.awadia

01/31/2019, 12:56 PM
Thanks! Makes sense
6 Views