android - Jetpack Compose 中的副作用

标签 android android-jetpack-compose side-effects

我了解到,除了 composable 中的 composition 行为外,所有其他行为都是副作用。那么,对于 TextField,在 onValueChange 中更改 TextFieldValue 是否有副作用?此外,在 composable 中显示 toast 消息是否有副作用?

最佳答案

让我们首先了解一些函数式编程方面的术语

幂等 - 意味着调用相同的函数 n 次,提供相同的输入,应该产生相同的输出。

您的函数在组合世界中需要幂等,以便重组工作 - 作为组合运行时,memoizes 在初始组合期间,如果在重组期间输入函数没有改变(或者说树节点没有更新),compose 运行时将使用相同的 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.

正如我们所说,函数应该没有副作用,但是在少数情况下,我们需要从可组合中运行副作用,为了处理这些情况,compose 运行时提供了不同的 effect-handlers , - 这将确保它们根据 compose 生命周期在正确的时间运行。

So, in the case of TextField, is changing the TextFieldValue in onValueChange a side effect?

它看起来更像是 unidirectional数据流向我,并且由于状态是在可组合项(可组合项的内部内存)范围内管理的,所以这不是副作用。

Also, is it a side effect to display a toast message in composable?

这可能是一个副作用,如果效果处理不当,考虑到,你最终不会在重新组合时调用 toast。

关于android - Jetpack Compose 中的副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69233520/

相关文章:

Android,正确使用 HTMLCleaner

android - 线圈图像缓存不适用于 Jetpack Compose

C++宏副作用

unit-testing - 具有副作用的单元测试功能?

clojure - 在 Clojure 中处理数据库读取

android - 在 TextView 中支持 <span> 标签的方法

java - 闹钟不起作用

Android - OnClickListener 和 OnLongClickListener 问题

android - 为什么指示不适用于按钮或图标?

android - 如何在 Jetpack Compose 中引用主题属性?