asad.awadia
01/31/2019, 2:45 AMgildor
01/31/2019, 2:49 AMasad.awadia
01/31/2019, 2:49 AMgildor
01/31/2019, 2:49 AMgildor
01/31/2019, 2:49 AMasad.awadia
01/31/2019, 2:50 AMbdawg.io
01/31/2019, 2:53 AMsuspend
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. suspend fun foo(): Int { ... }
suspend fun bar(): Int { ... }
suspend fun doSomething() = coroutineScope {
val fooAsync = async { foo() }
val barAsync = async { bar() }
foo.await() + bar.await()
}
gildor
01/31/2019, 3:02 AMgroostav
01/31/2019, 3:04 AMfoo
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
.bdawg.io
01/31/2019, 3:17 AMfoo()
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 completedbdawg.io
01/31/2019, 3:20 AMasync
coroutines depends on having enough threads for each coroutine to occupy.asad.awadia
01/31/2019, 12:56 PM