Skip to content

ObservableCollectionChanged shouldn't increment -1 indices for adds #89

@erri120

Description

@erri120

The R3 extension method ObserveChanged converts NotifyCollectionChangedEventArgs where IsSingleItem = false into multiple CollectionChangedEvent notifications. There is a consistency issue when the source collection isn't indexed (eg ObservableHashSet):

var collection = new ObservableHashSet<int>();
collection.AddRange(items: [1, 2, 3]);

This AddRange operation creates the following notifications:

{
  "Action": "Add",
  "NewItem": 1,
  "OldItem": 0,
  "NewStartingIndex": -1,
  "OldStartingIndex": -1,
  "SortOperation": {
    "Index": 0,
    "Count": 0,
    "Comparer": null,
    "IsReverse": false,
    "IsClear": true,
    "IsSort": false
  }
},
{
  "Action": "Add",
  "NewItem": 2,
  "OldItem": 0,
  "NewStartingIndex": 0,
  "OldStartingIndex": -1,
  "SortOperation": {
    "Index": 0,
    "Count": 0,
    "Comparer": null,
    "IsReverse": false,
    "IsClear": true,
    "IsSort": false
  }
},
{
  "Action": "Add",
  "NewItem": 3,
  "OldItem": 0,
  "NewStartingIndex": 1,
  "OldStartingIndex": -1,
  "SortOperation": {
    "Index": 0,
    "Count": 0,
    "Comparer": null,
    "IsReverse": false,
    "IsClear": true,
    "IsSort": false
  }
},

Note that NewStartingIndex gets incremented from -1 to 0 to 1. This is because of this snippet of code:

var i = eventArgs.NewStartingIndex;
foreach (var item in eventArgs.NewItems)
{
var newArgs = new CollectionChangedEvent<T>(
eventArgs.Action,
item,
eventArgs.OldItem,
i++,
eventArgs.OldStartingIndex,
eventArgs.SortOperation);
observer.OnNext(newArgs);
}

I believe that NewStartingIndex should be -1 for all three notifications.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions