我正在尝试创建一个 observable(此处为 fixedObservable),它将由多个动态创建的 observable 随时间提供。每当进行订阅时,订阅者都应该从 fixedObservable 获取最新值。虽然我已经实现了,但我想知道是否有任何简单的解决方案。你可以在这里找到代码https://jsfiddle.net/dzm2t3pa/8/。
谢谢
var resultdiv = document.getElementById('result');
function print(message) {
var paraEl = document.createElement('p');
paraEl.innerHTML = message;
resultdiv.appendChild(paraEl);
}
var startTime = new Date();
var fixedObservable = new Rx.Subject();
var subscription;
function subscribe() {
subscription = fixedObservable.subscribe(function(value) {
print('subscriber 1:' + value + ' :after ' + (new Date() - startTime) / 1000 + ' secs');
});
}
function unsubscribe() {
subscription.unsubscribe();
}
// Subscribe to the fixedObservable(i.e Subject) initiallly
subscribe()
//Unsubscribe and resubscribe after 11 sec here to see what
// happens in that period.
//Observation: The values generated in that period are not received as needed.
setTimeout(unsubscribe, 11000);
setTimeout(subscribe, 22000);
//just a simple check with multiple subscribers later.All the
//subscribers get the latest value.
/*setTimeout(function(){
fixedObservable.subscribe(function(value){
print('subscriber 2:'+value+' :after '+(new Date()-startTime)/1000+' secs');
});
},30000);*/
//setTimeout(function(){},)
//Initial Observables which feed the data to fixedObservable
var dynamicObservable1 = Rx.Observable.interval(4000);
var dynamicObservable2 = Rx.Observable.interval(5000);
var counter1 = 0;
//subscribe to dynamic observable and pass the data to fixedObservable
dynamicObservable1.subscribe(function(value) {
counter1 += 1;
fixedObservable.next(counter1 + 'th value from 1');
});
var counter2 = 0;
dynamicObservable2.subscribe(function(value) {
counter2 += 1;
fixedObservable.next(counter2 + 'th value from 2');
});
//create a dynamicObservable after 5secs to feed the data and
// then destroy it after 2.5 sec i.e at 7.5 sec from start.
//Observation: 2 value from this stream is received and then stops
setTimeout(function() {
var counter3 = 0;
var dynamicObservable3 = Rx.Observable.interval(1000);
var subs = dynamicObservable3.subscribe(function(value) {
counter3 += 1;
fixedObservable.next(counter3 + 'th value from 3');
});
setTimeout(function() {
subs.unsubscribe()
}, 2500)
}, 5000);
setTimeout(function() {
unsubscribe();
}, 50000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.min.js"></script>
<div id="result">
</div>