Handling collections
slimshader opened this issue · 2 comments
Hi,
first of all: fantastic project, always great to see solutions that promote declarative designs. Looking forward to updates to UniMob.UI too.
Question tho: do I understand correctly that collections (like Todo[] array) have to be replaced entirely for Atom to detect changes? (So basically it should be be treated as immutable collection) As in this would not work as expected, correct?:
[Atom] public List<Todo> Todos { get; set; } = new List<Todo>();
incrementButton.onClick.AddListener(() =>
{
Todos.Add(new Todo());
});
Atom.Reaction(() => counterText.text = "Unifinished: " + UnfinishedTodoCount);
Hi,
Yes that's right. Atom doesn't track object modification. Reaction will be triggered only when new value has been set for atom.
However, you can write your own collection type that will trigger reactions when new items are added.
[Atom] public AtomList<Todo> Todos { get; set; } = new AtomList<Todo>();
incrementButton.onClick.AddListener(() =>
{
Todos.Add(new Todo());
});
Atom.Reaction(() => counterText.text = "Unifinished: " + UnfinishedTodoCount);
public class AtomList<T> : IEnumerable<T>
{
private readonly MutableAtom<List<T>> _list = Atom.Value(new List<T>());
public void Add(T value)
{
_list.Value.Add(value);
_list.Invalidate();
}
public IEnumerator<T> GetEnumerator() => _list.Value.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
Here _list.Invalidate()
method will trigger reactions in the same way as if the collection were replaced with a new one.
Thanks, I see, Invalidate() is the key to custom atom semantics.