RxJS-暂停,恢复后给出最后一个暂停的值

Thi*_*ibs 5 rxjs rxjs5

我有一个可观察到的火热的套接字。我可以使用暂停按钮暂停套接字供稿。但是,一旦“取消暂停”可观察对象,我就需要显示暂停订阅时套接字可以发送的最后一个值。我不想跟踪套接字手动发送的最后一个值...这怎么可能呢?

在文档中的示例中,请参见以下注释:

var pauser = new Rx.Subject();
var source = Rx.Observable.fromEvent(document, 'mousemove').pausable(pauser);

var subscription = source.subscribe(
    function (x) {
        //somehow after pauser.onNext(true)...push the last socket value sent while this was paused...
        console.log('Next: ' + x.toString());
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });

// To begin the flow
pauser.onNext(true); 

// To pause the flow at any point
pauser.onNext(false);  
Run Code Online (Sandbox Code Playgroud)

pau*_*els 8

你甚至不需pausable要这样做。(还要注意,您标记了 RxJS5 但pausable仅存在于 中RxJS 4)。您只需要将您的pauser转换为更高的顺序Observable

var source = Rx.Observable.fromEvent(document, 'mousemove')
  // Always preserves the last value sent from the source so that
  // new subscribers can receive it.
  .publishReplay(1);

pauser
  // Close old streams (also called flatMapLatest)
  .switchMap(active => 
    // If the stream is active return the source
    // Otherwise return an empty Observable.
    Rx.Observable.if(() => active, source, Rx.Observable.empty())
  )
  .subscribe(/**/)

//Make the stream go live
source.connect();
Run Code Online (Sandbox Code Playgroud)

  • 感谢 Paul 的回复,但我是 rxjs 的新手,很抱歉我不完全理解上面的例子。暂停者和活动者从哪里来?它与源有什么关系?我没有看到联系...谢谢 (2认同)