Andrew Theken
Andrew Theken

Reputation: 3480

ReactiveKit: How do you get the values of changed entries for ObservableCollection?

I'm using ReactiveKit 1.x. It has a very helpful ObservableCollection<T>, which allows you to monitor for changes to a collection. In my case, I'm using it with Dictionary<String,String>

The ObservableCollection produces an event of type CollectionEventChange<T>, and it includes properties for insert, update, delete. For dictionary, these are DictionaryIndex<String,String>.

In order to examine the contents of delete and update entries, it seems like I need to keep a reference to the previous collection.

Is it possible to use the elements listed in these properties to look up the changed entry in the event's collection property?

Am I missing something? (I guess the solution might not have anything to do with ReactiveKit, just general use of Swift Dictionaries.)

Upvotes: 5

Views: 929

Answers (1)

Srđan Rašić
Srđan Rašić

Reputation: 1787

I think you should go with zipPrevious method to get previous event and from it the previous collection.

let collection = ObservableCollection(["key": "value"])

collection.zipPrevious().observe { (old, new) in
  guard let old = old else { return } // `old == nil` on first event

  for index in new.deletes {
    let value = old.collection[index]
    print("Deleted \(value).")
  }
}

Upvotes: 8

Related Questions