2014-10-30 66 views
2

如果我使用$ createObservableFunction方法创建一个observable并且我多次订阅该可观察值。最后的用户覆盖任何其他用户。

但是,如果我使用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'); 
    }); 


}); 

举例说明问题的解决方案。 http://plnkr.co/edit/kXa2ol?p=preview

+1

所以我想我找出了为什么它不起作用。 $ createObservableFunction()使用Rx.Observable.create()方法返回订阅者的SingleCast实现。为了多播它,你需要做$ createObservableFunction().black().refCount()来保持与源的连接。 – 2014-10-31 01:44:59

+0

为了记录,rx.angular的更新版本默认是这样做的。 – PhiLho 2015-11-24 11:22:03

回答

1

您必须分享观察者。看看这个plunker:http://plnkr.co/edit/4cVzpNVAel2Izcqg60Ci

它和你的代码完全一样,但它有.share()。

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

我不完全理解冷热观察者之间的区别,但基本上,当你分享它时,你会让观察者变得很热。这里有一篇可爱的文章,帮助我更好地理解:http://jaredforsyth.com/2015/03/06/visualizing-reactive-streams-hot-and-cold/和一个web应用程序,它可以让你看到你的代码,就像文章显示的那样:http://jaredforsyth.com/rxvision/examples/playground/