2

If I create an observable utilizing the $createObservableFunction method and I subscribe to that observable multiple times. The last subscriber overrides any other subscriber.

However if I create an observable with rx.Observable.interval() and subscribe to that multiple times. Both subscribers fire on the interval.

Why? More importantly how do I get the $createObservableFunction to fire both subscribers.

app.controller('MainCtrl', function($scope, rx) {

  var test = $scope.$createObservableFunction('testClick');
  var test2 = rx.Observable.interval(3000);


  test.subscribe(function(){
    console.log('I never run, why?');
  });

  test.subscribe(function(){
    console.log('Why am I overriding the above subscribe');
  });


  test2.subscribe(function(){
    console.log('This observable runs both subscribed functions')
  });

  test2.subscribe(function(){
    console.log('See this gets called and so does the above');
  });


});

Example plunker that illustrates the issue. http://plnkr.co/edit/kXa2ol?p=preview

Jonathan Sheely
  • 501
  • 1
  • 6
  • 13
  • 1
    So I think I figured out why it doesn't work. $createObservableFunction() uses the Rx.Observable.create() method which returns a singleCast implementation of the subscriber. In order to multicast it you need to do $createObservableFunction().publish().refCount() to keep the the connection to the source. – Jonathan Sheely Oct 31 '14 at 01:44
  • For the record, newer versions of rx.angular do that by default. – PhiLho Nov 24 '15 at 11:22

1 Answers1

1

You have to share the observer. Check out this plunker: http://plnkr.co/edit/4cVzpNVAel2Izcqg60Ci

It's the exact same as your code, but has the .share() on it.

var test = $scope.$createObservableFunction('testClick').share();

I don't fully understand the difference between hot and cold observers, but basically, you're making the observer hot when you share it. Here is a lovely article that helped me understand somewhat better: http://jaredforsyth.com/2015/03/06/visualizing-reactive-streams-hot-and-cold/ and a webapp that allows you to see YOUR code, in the same way that article shows: http://jaredforsyth.com/rxvision/examples/playground/

LadyCailin
  • 849
  • 10
  • 26