Behavior Subject Knockout Observable Performance

139 Views Asked by At

I'm working on a project where I have a singleton running across the application. This singleton offers an observable that view models can subscribe to. Upon subscription the subscriber should get the latest data from the observable, then continue to listen for further data.

Basically I'm looking for a RxJS BehaviorSubject implementation in Knockout.

I'm new to KO. I've got a working extender but I'm unsure if what I've done is going to cause issues.

This is my extender:

require(['knockout'], function(ko) {
  ko.extenders.subscribeWithLatest = function (target) {
    var _subscribe = target.subscribe;
    target.subscribe = function (callback) {
      var subscription = _subscribe.apply(this, arguments);
      var currValue = target.peek();
      if (currValue) {
        // I'm using setTimeout to stop the value from being
        // provided before the subscription is returned.
        // I'm not proud of this.
        setTimeout(() => {
          try { callback(currValue); } catch(e) {} }
        );
      }
      return subscription;
    };
    return target;
  };
});

The above code does work as I want, but I'm not sure about its efficiency.

1

There are 1 best solutions below

1
Ben Petersen On

It's a little messy for what it's actually doing (subscribe, peak, wait, get value). Have you tried going more simple like this?

myViewModel.personName.subscribe(function(newValue) {
   alert("The person's new name is " + newValue);
});

Knockout doesn't quite have the RxJS Behavior Subject and frankly it's not always needed.