2014-10-30 61 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/