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

Lucas

08/02/2022, 1:27 AM
I dont understand this. The warning says suspending fun has a CoroutineScope receiver, but the second class fails to find the "launch" method. Is this a bug or am i really misunderstanding this?
t

Trevor Stone

08/02/2022, 1:37 AM
Not sure exactly what you're trying to do, but
Copy code
class Test{
 suspend fun test() = coroutineScope{
 launch{ do things}
}
}
might be what you're looking for
but that launch will stop returning from test() until it completes
l

Lucas

08/02/2022, 1:41 AM
Well, i'm trying to use coroutines with JavaFX, but that doesnt seem to be very usual and i didnt find much on it apart from the Dispatchers.JavaFX (or Main) One elegant solution i found was to make my components extend the CoroutineScope and clear it accordingly to javafx components lifecycle The classes were minimal reproducers But regardless of what i'm trying to do, i still dont quite understand the warning. Why cant i call launch from a suspending function?
Ok i tried your code and i makes a bit more sense now. Still some things i need to figure out tho, thanks!
i

Ivan Pavlov

08/02/2022, 6:11 AM
Your outer class "test" implements coroutinescope, so launch in your function is
this.launch
c

Chrimaeon

08/02/2022, 3:28 PM
You are already in a suspend function. There is no need to
launch
a coroutine. That's what the warning is telling you.
l

Lucas

08/02/2022, 4:02 PM
I dont think thats it @Chrimaeon
Copy code
suspend fun test() {
 launch{ do things}
 do other things
}
What if i wanted this? It would still show a warning
i

Ivan Pavlov

08/02/2022, 4:03 PM
To get access to coroutine scope in suspending function you can do
Copy code
suspend fun test() {
  coroutineScope {
    // access scope here
  }
}
c

Chrimaeon

08/02/2022, 4:10 PM
Sure, but then also you’ll need to wrap the
launch
in a “new”
coroutineScope{}
like already mentioned, to give the job it’s own inner scope
l

Lucas

08/02/2022, 4:11 PM
Yeah i think i was misunderstanding some basic concepts about context vs scope
Like why could i use withContext but not launch
t

Trevor Stone

08/02/2022, 4:23 PM
withContext provides a coroutineScope in the block and doesn't require one to run
l

louiscad

08/07/2022, 8:53 AM
Implementing CoroutineScope is the problem. Should have a private property instead, and use
coroutineScope { }
inside suspend functions.
4 Views