Skip to content

Instantly share code, notes, and snippets.

@Andrew0000
Last active January 27, 2023 19:14
Show Gist options
  • Save Andrew0000/b5e033c7eca3d5c5c3722e1ac191c590 to your computer and use it in GitHub Desktop.
Save Andrew0000/b5e033c7eca3d5c5c3722e1ac191c590 to your computer and use it in GitHub Desktop.
remember {} with key is same as derivedStateOf
@Composable
fun ATest() {
val frequentlyChangedState = remember { mutableStateOf(0) }
LaunchedEffect(Unit) {
launch {
delay(5000) // delay so you can attach with Layout Inspector if you don't trust logs enough.
while (frequentlyChangedState.value < 10) {
delay(200)
frequentlyChangedState.value++
}
}
}
val valueToDisplay = remember(frequentlyChangedState.value) {
frequentlyChangedState.value / 2
}
Timber.i("test_ ATest outer") // 1 initial composition + 10 recompositions
ATestInner(valueToDisplay)
}
@Composable
fun ATestInner(value: Int) {
Timber.i("test_ ATestInner") // 1 initial composition + 5 recompositions
Text(text = "value: $value")
}
@Andrew0000
Copy link
Author

Well, looks like crucial distinction is that remember {} is Composable whereas derivedStateOf {} not and therefore a new State stream can be created even outside Composable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment