简体   繁体   中英

Could you give me some sample code to prove Never depend on side-effects from executing composable functions?

The following content is from the article .

Never depend on side-effects from executing composable functions, since a function's recomposition may be skipped. If you do, users may experience strange and unpredictable behavior in your app. A side-effect is any change that is visible to the rest of your app. For example, these actions are all dangerous side-effects:

Writing to a property of a shared object
Updating an observable in ViewModel
Updating shared preferences

It says that there are three case to cause recomposition be skipped, but it doesn't give me sample code.

Epecially, I convert a LiveData which is observable to State<T> for Compose, the UI will be updated automatically when the value of the LiveData is updated!

Could you give me some sample code to prove Never depend on side-effects from executing composable functions ?

I do not know Jetpack, but I presume the idea is that UI refresh will only be triggered by a State change. In other words, only Composable functions that depend on a State will update.

Okay (better would be if we extracted the state and the callback, but just for the example) :

@Composable
fun Example() {
    var counter by remember { mutableStateOf(0) }
    Row {
        Text(counter.toString())
        Checkbox(checked = value, onCheckedChange = { counter++ })
    }
}

Bad Side-Effects:

object GlobalCounterState {
    var counter = 0
}

@Composable
fun Example() {
    Row {
        Text(GlobalCounterState.counter.toString())
        Checkbox(checked = value, onCheckedChange = { GlobalCounterState.counter++ })
    }
}

Side-effects is anything that leaves the function scope. For example, external mutations (such as in the example above) or UI changes (such as calling a Toast/Snackbar) or clearing a disposable/subscription. In JetPack Composable functions can re-run at any time and any number of times. It needs to be pure and deterministic. Meaning, given the same input, the effect or result must be identical regardless if called 10 or 1000 times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM