Skip to content

Instantly share code, notes, and snippets.

@AfzalivE
Last active October 29, 2024 15:30
Show Gist options
  • Save AfzalivE/194f807c1f5fc3a88b4716f6ff8bb36a to your computer and use it in GitHub Desktop.
Save AfzalivE/194f807c1f5fc3a88b4716f6ff8bb36a to your computer and use it in GitHub Desktop.
A jetpack compose preview demonstrating the effects of recomposition for a snapshot flow.

Output of LaunchedEffect(Unit) on 3 button clicks

collected value
collected value
collected value

Output of LaunchedEffect(someState) on 3 button clicks.

collected value
Recreating snapshot flow
collected value
collected value
Recreating snapshot flow
collected value
collected value
Recreating snapshot flow
collected value

Each click causes

collected value
Recreating snapshot flow
collected value
@Preview
@Composable
private fun SnapshotFlowPreview() {
var someState by remember { mutableStateOf("") }
var someOtherState by remember { mutableStateOf("") }
val onSomeStateChange: (String) -> Unit = { newState ->
someOtherState = newState
}
// Replace this line with the commented one.
LaunchedEffect(someState) {
// LaunchedEffect(Unit) {
debug("SnapshotFlowPreview", "Recreating snapshot flow")
snapshotFlow { someState }.collect {
debug("SnapshotFlowPreview", "collected value")
onSomeStateChange(it)
}
}
Column {
Text("Some state: $someState")
Text("Other state: $someOtherState")
Button(onClick = { someState = Random.nextInt().toString() }) {
Text("change state")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment