Reputation: 1301
I understood that other than the act of composition
in composable
, all other actions were side effects. So, in the case of TextField
, is changing the TextFieldValue
in onValueChange
a side effect? Also, is it a side effect to display a toast message in composable
?
Upvotes: 2
Views: 1766
Reputation: 3349
Let's first understand few terms w.r.t functional programming
Idempotent
- means calling the same function n times, providing the same input, should result in same output.
Your function needs to be idempotent
in compose world, for the recomposition to work - as compose runtime, memoizes
during initial composition, and if during recomposition the input of the function have't changed (or say the tree node isn't updated), compose runtime will use the same memoized
result. Having a function not being idempotent
will lead to unexpected behaviour during recomposition.
Purefunction
- Functions that don't contain side-effect.
Side-effect
- it's any action that escapes the scope of the function to do something unexpected on the side.
In compose world - side-effect could be a change to the state of the app that happens outside of the scope of the function, things like setting a global variable, updating cache, making a network query, reading from file etc..
It makes the function non-deterministic and can lead to race condition and unexpected behavior.
To generalize, side-effects are unexpected actions happening on the side, out of what callers would expect from the function, and that alter its behavior.
As we say a function should be side-effect free, however in few scenarios we need to run a side-effect from composable, to handle those cases compose run-time provides different effect-handlers, - which will makes sure, they run at the right time with accordance to the compose lifecycle.
So, in the case of TextField, is changing the TextFieldValue in onValueChange a side effect?
It more looks like an unidirectional data flow to me and the since the state is managed within the scope of composable (internal memory of composable), it's not a side-effect.
Also, is it a side effect to display a toast message in composable?
It can be a side-effect, if the effect is not handled properly, considering, you are not ending up getting the toast called, on ever recomposition.
Upvotes: 8
Reputation: 1378
According to defination of SideEffect in Jetpack Compose, A side-effect is a change to the state of the app that happens outside the scope of a composable function. In TextField, we can't change state of textfield we swape the value. You can see it in CoreTextField Compose funtion:
if (value != it) {
onValueChange(it)
}
},
So in onValueChange, no SideEffects use.
Also in the case of Toast message, yet Toast is not written in Compose so it is not a compose function and we can call it from outside of compose function so there is no side effect use.
Upvotes: 3