如何暂停可观察对象

How to pause an observable

如何真正暂停 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/

我希望控制台中出现 start 消息,就在 subscribe 之后,比 1s 中断,比一个 subscribe 消息,比 2s 中断,最后 subscribe

但在一秒钟的休息后,我立即收到了最后两条 订阅 消息。好像我只能暂停 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')