android - Jetpack Compose 中的副作用
问题描述
我知道除了 in 的行为之外composition
,composable
所有其他行为都是副作用。那么,在 的情况下TextField
,是否会TextFieldValue
产生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.
正如我们所说的那样,函数应该没有副作用,但是在少数情况下,我们需要从可组合运行副作用,以处理这些情况,组合运行时提供不同的效果处理程序,-这将确保它们运行在根据撰写生命周期的正确时间。
那么,在 TextField 的情况下,更改 onValueChange 中的 TextFieldValue 是否会产生副作用?
在我看来,它更像是单向数据流,并且由于状态是在可组合(可组合的内部存储器)范围内管理的,因此它不是副作用。
另外,在可组合中显示吐司消息是否有副作用?
这可能是一个副作用,如果没有正确处理效果,考虑到你最终不会在重新组合时调用吐司。
推荐阅读
- python-3.x - 在 py_environment.PyEnvironment 类中定义 TF-Agents 操作
- python - How to combine different field types in flask-wtf wtforms
- kotlin - Kotlin Multiplatform 中的 kapt - 默认情况下 gradle 和 IDE 无法识别 src 目录
- python - 在python中用类变量覆盖开槽属性
- angular - 在 Konva 中逐步调整矩形大小
- python - Doc2Vec build_vocab 方法失败
- c++ - if then C++中的三元运算符
- azure - 如何确定 Azure 虚拟机是否(未)托管?
- python - 功能。ValueError:使用可迭代设置时必须具有相等的 len 键和值。熊猫
- java - 未找到 ID 为 com.android.application 的插件