Hi ! I'm having an issue with coroutine in a Jetpa...
# coroutines
l
Hi ! I'm having an issue with coroutine in a Jetpack Compose for Desktop project. More in the thread 🧵 .
✅ 1
In my
@Composable
, I've createad a function
startClockIfAppropriated
, but it seems that the coroutine I'm trying to launch inside it never start.
All I get is a message "Ready to start clock coroutine !"
Any help appreciated 🙂
This is the complete source file. Apologizing for my very ugly style.
s
When are all these inner-functions called (especially the one you're asking about
startClockIfAppropriated
)?
l
In this
startNewGame()
function, I'm calling
startClockIfAppropriated()
. And I'm calling this function
startNewGame()
when the user clicks on a button. What happens here is that I'm passing a callback function to the `Screen.EditPosition`page of the function
navigation.push()
so that it will be executed when we're back in the game screen if the user validated the new (chess) position they edited in this
EditPosition
screen.
s
I'm a bit worried about the inner functions, where you capture implicitly the stack-frame of a
@Compose
function. I can imagine that the
rememberCoroutineScope
returns a CoroutineScope that may be cancelled or in a state that it can't launch coroutines. Try moving all your functions outside of your (top)
@Compose
function, make them global, and instead add parameters for those variable that you implicitly captured.
l
Thank you. I'll try to refactor the
@Compose
function
I don't know how to proceed, because of the number of state variables in the `@Composable`function. And I'm sure I can't use
ViewModel
because it belongs to Android.
s
You can put state in StateHolders instead, ViewModels are not required.
l
Thank you very much. I'm gonna have a look at those StateHolders 🙂
s

https://youtu.be/pCX9wvu-Bq0â–¾

8m:55s in this video
l
Thank you very much 🙂 I'm gonna learn from it 🙂
s
And here's a Bootcamp, self guided https://developer.android.com/compose-camp
l
I've removed all states from the GamePage
@Composable
, using two state holders instead. GamePageLogicState and GamePageClockState .
The good news is that the application works as before. The bad news is that I'm still having issue with the clock coroutine, which seems to have been cancelled before the time I need to start the clock. (I've just printed the context of the coroutine's job and I noticed that)
As the only cancellation I'm doing is happening once the clock is launched, I bet I've got an exception in the coroutine context. But neither adding an exception handler, not using try/catch helped me see any kind of error. So I'm stuck.
I found the issue, and learned something new on the same occasion. The coroutine was created in the GamePage composable, which I left when letting user edit its custom chess position, and so it was cancelled, as the GamePage was not in the scope anymore.
So I needed a way to hoist the coroutine scope.