Ji *_*bin 2 android side-effects android-jetpack-compose
我明白除了compositionin的行为之外composable,所有其他行为都是副作用。那么,在 的情况下TextField,更改TextFieldValuein会onValueChange产生副作用吗?另外,在 中显示 toast 消息是否有副作用composable?
让我们首先了解函数式编程的几个术语
Idempotent- 意味着调用相同的函数n次,提供相同的输入,应该产生相同的输出。
您的函数需要位于idempotent组合世界中,以便重新组合工作 - 作为组合运行时,memoizes在初始组合期间,如果在重新组合期间函数的输入未更改(或者说树节点未更新),则组合运行时将使用相同的memoized结果。函数不存在idempotent将导致重组期间出现意外行为。
Purefunction- 不包含副作用的函数。
Side-effect- 它是任何逃离函数范围以在侧面执行意外操作的操作。
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.
Run Code Online (Sandbox Code Playgroud)
正如我们所说,函数应该没有副作用,但是在少数情况下,我们需要从可组合项运行副作用,为了处理这些情况,组合运行时提供了不同的效果处理程序,-这将确保它们运行在根据撰写生命周期的正确时间。
那么,就 TextField 而言,在 onValueChange 中更改 TextFieldValue 是否会产生副作用?
对我来说,它更像是单向数据流,并且由于状态是在可组合项(可组合项的内部存储器)范围内管理的,因此它不是副作用。
另外,在可组合项中显示 toast 消息是否有副作用?
如果效果处理不当,考虑到在重组时您最终不会调用 toast,这可能是一个副作用。
| 归档时间: |
|
| 查看次数: |
1632 次 |
| 最近记录: |