2

如果我使用 $createObservableFunction 方法创建了一个可观察对象,并且我多次订阅该可观察对象。最后一个订阅者覆盖任何其他订阅者。

但是,如果我使用 rx.Observable.interval() 创建一个 observable 并多次订阅它。两个订阅者都在间隔开火。

为什么?更重要的是如何让 $createObservableFunction 触发两个订阅者。

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');
  });


});

说明问题的示例 plunker。http://plnkr.co/edit/kXa2ol?p=preview

4

1 回答 1

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/

于 2015-09-15T22:16:19.143 回答