Hi guys, if I want to declare an interface with a ...
# coroutines
a
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
I think every suspend function runs in the scope of the caller. No extension need there.
a
gotcha, so you go either with suspend modifier or with CoroutineScope. extension function?
g
Definitely suspend (if you don’t have some very specific use case for it)
a
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
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
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
gotcha, alright makes sense, thanks guys
g
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
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
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
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