【问题标题】:How to pause an observable如何暂停一个 observable
【发布时间】:2015-04-22 02:07:29
【问题描述】:

如何真正暂停 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 之后,1 秒中断,subscribe 消息,2 秒中断,以及最后一个订阅

但在一秒钟的休息之后,我立即收到了最后两条 订阅 消息。好像我只能暂停一次可观察对象。

对于那些对我想要实现什么感兴趣的人:我想要一个事件队列,并且我想接收下一个事件,如果为前一个事件调用了一些回调(事件完成。现在是只是一个简单的 setTimeout)

【问题讨论】:

    标签: javascript rxjs


    【解决方案1】:

    pausableBuffered 在暂停时保留一个缓冲区并在调用 resume 时耗尽缓冲区。你想要的看起来更像是一个受控的 observable,你说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')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-17
      • 2021-08-31
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多