Hello All,
# compose
d
Hello All,
I have a query regarding the coroutine in composable. I'm running an animation which rotates the icon 360 degree. What i'm doing is that in my ViewModel I have a method which which sets the value for the StateFlow of type boolean. Which i'm also collectingAsState in the composable. So I set it to True using a coroutine which is repeating after a delay of 10s. And i set it false from when the api is finished.
Copy code
val isRotated = questionnaireViewModel.autoSaveStateFlow.collectAsState()
var currentDateTime = LocalDateTime.now()

    val angle: Float by animateFloatAsState(
        targetValue = if (isRotated.value) 360F else 0F,
        animationSpec = tween(
            durationMillis = 3000,
            easing = FastOutSlowInEasing
        )
    )

coroutineScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
    //repeate Task Here
    delay(10000)
    questionnaireViewModel.setAutoSaveState(true)
    Log.i("👀mylog", "run: running animation")
}
this is the code snippet for the above
What i'm seeing is that coroutine function works fine for the first time but as the composable goes for recomposition because of the isRotated value change, coroutine runs multiple times
What i'm i missing ?
a
Aren't you getting a lint error on
coroutineScope.launch
saying
Calls to launch should happen inside a LaunchedEffect and not composition
?
d
No i'm not getting a lint error. But i was originally using this inside a Launched Effect, but then i want this to keep running.
So ideally i thought it will be running once every time the composition recomposes, but it is running multiple times
a
running once every time the composition recomposes
This is likely wrong. Why do you want this?
Remember that recomposition can be triggered any times at any time. You shouldn't rely on when or how often it happens for correctness.
d
I want to have a service/task which runs every let's say 10 seconds. It basically saves the data entered by the user in the form that we are displaying.
a
Then this should do.
Copy code
LaunchedEffect(questionnaireViewModel) {
    while (true) {
        dalay(10000)
        questionnaireViewModel.setAutoSaveState(true)
    }
}
d
Okay i see. Thanks that works