Skip to content

Sharing some utilities from real-world code #36

@nadako

Description

@nadako

Sometimes (mostly for the purpose of animations) we want to differentiate between initial binding and update callbacks, as well as having previous value at hand. This can be achieved by some basic extension methods that wrap the callbacks and provide additional information.

using System;
using TinkState;

static class ObservableExtensions
{
    public static IDisposable BindWithInitial<T>(this Observable<T> observable, Action<T, bool> callback)
    {
        var initial = true;
        return observable.Bind(value =>
        {
            if (initial)
            {
                initial = false;
                callback(value, true);
            }
            else
            {
                callback(value, false);
            }
        });
    }

    // this is not very elegant and may cause memory "leak" if T is something that holds a lot of memory...
    public static IDisposable BindWithPrevious<T>(this Observable<T> observable, Action<T, T> callback)
    {
        var previous = observable.Value;
        return observable.Bind(value =>
        {
            var old = previous;
            previous = value;
            callback(value, old);
        });
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions