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

voben

05/13/2020, 3:19 AM
I’d like to make a fire and forget network call, and don’t want to wait for the response. Will
doSomethingElse()
get called before the network call completes? How could I improve this?
Copy code
suspend fun signOut() {
     coroutineScope {
         launch {
             makeNetworkRequest() // suspending function
         }
     }
     doSomethingElse()
}
o

octylFractal

05/13/2020, 3:24 AM
no, it will not --
coroutineScope
will suspend until the
launch
is finished
if you want to launch it and break structured concurrency, then you need to have some other external
CoroutineScope
to start it on, or as a last resort you can use
GlobalScope
if you would just like to run it in parallel with
doSomethingElse()
, but still wait for it to complete before
signOut()
finishes, then move
doSomethingElse()
inside the
coroutineScope
block
g

gregd

05/13/2020, 2:26 PM
@voben Why not try it yourself and see it with your own eyes?
The answer is “yes”. doSomethingElse() gets called before makeNetworkRequest() completes.
…if you put doSomethingElse() inside coroutineScope() 😉
Play around with it. It’s easy with Kotlin Playground
v

voben

05/13/2020, 2:33 PM
thanks @gregd
g

gregd

05/13/2020, 2:38 PM
No worries. And thanks @octylFractal too :)
👍 1
5 Views