Rxjs observing object updates and changes

Andrew Mata picture Andrew Mata · Sep 20, 2015 · Viewed 26.9k times · Source

I am currently trying to observe any changes to a given object including all of it's elements.

The following code only fires when an object[x] is updates, but not if individually updating object[x]'s elements such as object[x][y]

<script>
  var elem = document.getElementById("test1");

var log = function(x) {
    elem.innerHTML += x + "<br/><br/><br/>";
};

var a = [{a:1,b:2},
         {a:2,b:5}
       ];


var source = Rx.Observable
.ofObjectChanges(a)
.map(function(x) {
    return JSON.stringify(x);
});


var subscription = source.subscribe(
    function (x) {log(x);},
    function (err) {log(err);},
    function () {log('Completed');}
);

a[0] = a[1];
</script>

This code runs and fires correctly.

however. if I instead to this

a[0]['a'] = 3;

Then nothing happens.

EDIT

A better way to phrase this, how can I observe changes from an array of objects?

Answer

electrichead picture electrichead · Sep 22, 2015

If you want only the nested object changes:

var source = rx.Observable.from(a).flatMap(function(item) {
  return rx.Observable.ofObjectChanges(item);
});

If you also want changes like a[0] = a[1]:

var source = rx.Observable.merge(
  rx.Observable.ofArrayChanges(a),
  rx.Observable.from(a).flatMap(function(item) {
    return rx.Observable.ofObjectChanges(item);
  })
);

The flatMap or selectMany (they are the same function) will allow you to iterate over a value and execute a function that returns an Observable. The values from all these Observables are "flattened" onto a new stream that is returned.

http://reactivex.io/documentation/operators/flatmap.html