Skip to content

Previous value of an Atom #6

Answered by vanifatovvlad
slimshader asked this question in Q&A
Discussion options

You must be logged in to vote

No, there is no way get the previous value of an atom. Alternatively, you can write reaction that remembers the previous value.

private void Start()
{
    Reaction(
        () => Counter,
        (current, previous) => Debug.Log($"Counter changed from {previous} to {current}")
    );
}

private static Reaction Reaction<T>(AtomPull<T> reaction, Action<T, T> effect)
{
    var hasPrevious = false;
    var previous = default(T);
    return Atom.Reaction(reaction, value =>
    {
        if (hasPrevious)
        {
            effect(value, previous);
        }

        previous = value;
        hasPrevious = true;
    });
}

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by vanifatovvlad
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #3 on July 21, 2021 13:36.