如何真正暂停 rxjs observable?
我有以下代码:
var pauser = new Rx.Subject();
var animation = new Rx.Subject();
var source = animation.pausableBuffered(pauser);
source
.subscribe(function(frame) {
console.log('subscribe', frame);
setTimeout(function() {
source.resume();
}, frame.duration);
source.pause();
});
pauser.onNext(true);
console.log('start');
animation.onNext({ duration: 1000 });
animation.onNext({ duration: 2000 });
animation.onNext({ duration: 2000 });
http://jsfiddle.net/bbvarga/8yvLhjhe/
我希望在 subscribe 之后控制台中出现 start 消息,比 1s 中断,比一个 subscribe 消息,比 2s 中断, 最后一个订阅
但在一秒钟的休息后,我立即收到了最后两条订阅消息。似乎我只能暂停一次 Observable。
对于那些对我想要实现的目标感兴趣的人:我想要一个事件队列,我想接收下一个事件,如果为前一个事件调用了一些回调(事件完成。现在是只是一个简单的 setTimeout)
最佳答案
pausableBuffered 在暂停时保留缓冲区,并在调用 resume 时清空缓冲区。您想要的看起来更像是一个受控的可观察对象,您可以在其中说 source.request(1)
。
参见 the rxjs docs on backpressure了解更多信息。
var animation = new Rx.Subject();
var source = animation.controlled();
source
.subscribe(function(frame) {
console.log('new event', frame);
setTimeout(function() {
console.log('after timeout', frame);
source.request(1);
}, frame.duration);
});
source.request(1);
animation.onNext({ duration: 1000 });
console.log('animation.onNext 1');
animation.onNext({ duration: 2000 });
console.log('animation.onNext 2');
animation.onNext({ duration: 3000 });
console.log('animation.onNext 3')
关于javascript - 如何暂停可观察对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29778457/