how to launch a coroutine inside a composable in Android Jetpack Compose
Answer #1 100 %The expression,
val color: MutableState = remember {
if (new.value)
mutableStateOf(Color(0xFFB9F6CA))
else
mutableStateOf(Color(0xFFFDFDFD))
}
should just be,
val color = if (new.value) Color(0xFFB9F6CA) else Color(0xFFDFDFD)
The lambda to remember
is only ever called once for the composition and is not considered invalid when new
changes. There is no need to remember
a Color()
value as it is fast enough that repeating it whenever new.value
is changes is not going to be a significant burden for composition.
Also, as Gabriele Mariotti suggested, use the composition scope instead of Global
. In this case, it doesn't matter much as it just potentially keeps the reference to new
alive for 2 seconds longer than needed but it is a very good habit to get into as, when you use the composition context the coroutine is cancelled automatically when the composition is no longer needed (such as the row scrolling off screen).
Also, if the color is not just a placeholder for seeing the effect of a coroutine, consider using animations for this as you would probably want the color to transition instead of snap.
Answer #2 100 %You can use the rememberCoroutineScope
function that returns a CoroutineScope
.
Something like:
// Create a CoroutineScope that follows this composable's lifecycle
val composableScope = rememberCoroutineScope()
composableScope.launch {
//... your code
}
More info here.