Reactions to nested Atoms #7
-
Hi, I think I am missing something still, code sample:
When running, I always only see values "5" or "7" printed but not "6". Is there a way to React to changes in multi-level Atoms? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
The reactions are executed in two cases:
In this sample, a value "5" is printed immediately when creating a reaction. Values "6" and "7" are set during one frame. They trigger a reaction, but the reaction itself is executed once on the next frame and use latest values (so "7" is printed). The value "6" will be printed if the values are set in different frames, or if you force actualize a reaction. private IEnumerator Start()
{
VM = new ViewModel() {IntValue = 5};
Atom.Reaction(() => Debug.Log($"Int value {VM.IntValue}"));
VM.IntValue = 6;
yield return null; // skip one frame
VM = new ViewModel() {IntValue = 7};
} private void Start()
{
VM = new ViewModel() {IntValue = 5};
var reaction = Atom.Reaction(() => Debug.Log($"Int value {VM.IntValue}"));
VM.IntValue = 6;
reaction.Activate(); // force actualize
VM = new ViewModel() {IntValue = 7};
} |
Beta Was this translation helpful? Give feedback.
-
Ah, makes perfect sense now. The fact that Reaction is only triggered next frame with latest value could be leveraged as optimization I suppose then, no need to discard intermediate updates to the values as they will not force UI update anyways. Question: could you clarify the difference between Reaction(Action reaction) and Reaction(AtomPull react, Action effect)? When to use which one? |
Beta Was this translation helpful? Give feedback.
-
Reaction(AtomPull react, Action effect) tracks atoms that used in react method, and won't track atoms in effect method. For example, this reaction: Atom.Reaction(() => {
var val = myAtom;
otherPlugin.Process(val);
}); will executed when myAtom value changed, but potentially otherPlugin can access other atoms in Process method, so reaction will track them too. If you dont want this behaviour, you can use Reaction(AtomPull react, Action effect) overload to control which data should be tracked. In this sample reaction wont track atoms used in Process method. Atom.Reaction(
() => myAtom,
val => otherPlugin.Process(val)
); Or you can use NoWatch Atom.Reaction(() => {
var val = myAtom;
using (Atom.NoWatch) {
otherPlugin.Process(val);
}
}); |
Beta Was this translation helpful? Give feedback.
The reactions are executed in two cases:
In this sample, a value "5" is printed immediately when creating a reaction. Values "6" and "7" are set during one frame. They trigger a reaction, but the reaction itself is executed once on the next frame and use latest values (so "7" is printed).
The value "6" will be printed if the values are set in different frames, or if you force actualize a reaction.