首页 > 解决方案 > Jetpack Compose 中的副作用

问题描述

我知道除了 in 的行为之外compositioncomposable所有其他行为都是副作用。那么,在 的情况下TextField,是否会TextFieldValue产生onValueChange副作用?另外,在 中显示 toast 消息是否有副作用composable

标签: androidandroid-jetpack-composeside-effects

解决方案


让我们首先了解函数式编程的几个术语

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 是否会产生副作用?

在我看来,它更像是单向数据流,并且由于状态是在可组合(可组合的内部存储器)范围内管理的,因此它不是副作用。

另外,在可组合中显示吐司消息是否有副作用?

这可能是一个副作用,如果没有正确处理效果,考虑到你最终不会在重新组合时调用吐司。


推荐阅读