Skip to content

OldViews are empty during source collection Clear() #94

@Serogriff

Description

@Serogriff

Hey

I've been looking into your project for a few days already. And I discovered some behavior that was not obvious to me when I was investigating the leak. The main problem is SynchronizedView send me an empty array, when source collection was resetted.
I made a small code example to demonstrate the situation.

public sealed class ProfileViewModel : IDisposable
{
    private readonly R3.CompositeDisposable _disposable = new();
    private readonly int _id;

    public ProfileViewModel(int id)
    {
        _id = id;
    }

    public void Dispose()
    {
        Console.WriteLine($"Profile {_id} disposed.");
        _disposable.Dispose();
    }
}

private static void Main(string[] args)
{
    ObservableList<int> arr = new();
    using var view = arr.CreateView(x => new ProfileViewModel(x));
    view.ViewChanged += (in SynchronizedViewChangedEventArgs<int, ProfileViewModel> e) =>
    {
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Remove:
            {
                if (e.IsSingleItem)
                {
                    e.OldItem.View.Dispose();
                }
                else
                {
                    foreach (var vm in e.OldViews)
                    {
                        vm.Dispose();
                    }
                }

                break;
            }
            case NotifyCollectionChangedAction.Reset:
            {
                foreach (var vm in e.OldViews)
                {
                    vm.Dispose();
                }

                break;
            }
        }
    };

    arr.Add(1);
    arr.Add(2);
    arr.Add(3);

    arr.Clear(); // e.OldViews are empty in event handler

    return;
}

Now, to workaround this problem, I do

for (var i = arr.Count - 1; i >= 0; i--)
{
    arr.RemoveAt(i);
}

instead of arr.Clear(); and I get what I originally expected.

So, bug or by design?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions