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

Aaron Waller

08/09/2021, 9:58 AM
Can someone explain to me whats the difference between
with(GlobalScope){ launch{} }
and
GlobalScope.launch{}
? All I can find is: "You can use
with()
in order to avoid the repetition of the
GlobalScope
receiver" but I don't really get it. Thanks in advance
a

andylamax

08/09/2021, 10:03 AM
You can't launch a coroutine by using
Copy code
with(GlobalScope) {
  // . . . 
}
You are gonna have to add launch like so
Copy code
with(GlobalScope) {
  launch {
    // . . . 
  }
}
While you can just launch a new coroutine like so
Copy code
GlobalScope.launch {
   // . . . 
}
a

Aaron Waller

08/09/2021, 10:05 AM
Yes, thanks I editet my question so it makes more sense. What is the usecase of using
with(GlobalScope){ launch{} }
?
a

andylamax

08/09/2021, 10:07 AM
just use
GlobalScope.launch
you are not getting any benefit by using
with
if all you are trying to do is just launch a corountine
also avoid the use of
GlobalScope
create your own scope if possible
m

marstran

08/09/2021, 10:22 AM
The
with
function is a stdlib function, not a coroutine function. Your examples will behave exactly the same.
p

PHondogo

08/09/2021, 10:26 AM
with - stdlib function that takes two parameters. One becomes the receiver for the second lambda parameter. For your case if you need to call launch several times its will be less code if use with.
3 Views