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

Andrea Giuliano

08/27/2020, 10:14 AM
Hi guys, if I want to declare an interface with a method that runs in the scope of the caller, is that ok to do something like
Copy code
interface MyGuy {
  suspend fun CoroutineScope.doSomething()
}
or is there a better way when it comes to interface declaration?
a

andylamax

08/27/2020, 10:16 AM
I think every suspend function runs in the scope of the caller. No extension need there.
a

Andrea Giuliano

08/27/2020, 10:17 AM
gotcha, so you go either with suspend modifier or with CoroutineScope. extension function?
g

gildor

08/27/2020, 10:18 AM
Definitely suspend (if you don’t have some very specific use case for it)
a

Andrea Giuliano

08/27/2020, 10:20 AM
one thing that made me suspicious is that if I have a suspend function, I can’t do launch inside.
Copy code
suspend fun doSomething() {
    launch {} // not possible
}
that’s because I’m not in a scope, so how to I make launch be running in the caller scope?
a

andylamax

08/27/2020, 10:20 AM
If all you are worried is scoping, go with suspend modifier. as an advice, given by @elizarov use CoroutineScope extension when your are creating another coroutine. It kinda makes the code self documenting and I do agree with him there
g

gildor

08/27/2020, 10:21 AM
It’s possible
just use coroutineScope function
Copy code
suspend fun doSomething() {
    coroutineScope {
         launch {} // Possible!
    }
}
It also not only possible, but properly implement structure concurrency
a

Andrea Giuliano

08/27/2020, 10:22 AM
gotcha, alright makes sense, thanks guys
g

gildor

08/27/2020, 10:23 AM
launching background task as side effect on external scope smells a lot, better to allow run it as suspend function, so user of this API can decide it to run on any scope
1
It was also recently discussed in this thread https://kotlinlang.slack.com/archives/C1CFAFJSK/p1597971811047400
a

andylamax

08/27/2020, 10:25 AM
adding onto @gildor I would normally do
Copy code
suspend function doSomenthing() = coroutineScope {
  launch{
    // do crazy things in here
  }
}
Just in case I need the instance of the calling scope, if not, I just call the function
g

gildor

08/27/2020, 10:26 AM
would like to point out, this code makes sense only if you have a few things run in parallel (or one thing + join()), otherwise this method is the same as:
Copy code
suspend function doSomenthing() = // do crazy things in here
✔️ 2
a

Andrea Giuliano

08/27/2020, 11:06 AM
makes sense, so if I want to build new coroutines starting from the calling scope, I do coroutineScope {} or else I can avoid using the scope builder and just what I need to inside the function, that will be called with the parent scope of the calling function in both cases
👌 2
2 Views