[RxJS] Implement pause and resume feature correctly through RxJS

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[RxJS] Implement pause and resume feature correctly through RxJS相关的知识,希望对你有一定的参考价值。

Eventually you will feel the need for pausing the observation of an Observable and resuming it later. In this lesson we will learn about use cases where pausing is possible, and what to do when pausing is impossible.

 

const resume$ = new Rx.Subject();

const res$ = resume$
  .switchMap(resume =>
    resume ?
      Rx.Observable.interval(2000) :
      Rx.Observable.empty()
  )
  .do(x => console.log(request it!  + x))
  .switchMap(ev => Rx.Observable.ajax({
    url: https://jsonplaceholder.typicode.com/users/1,
    method: GET,
  }));

res$.subscribe(function (data) {
  console.log(data.response);
});

resume$.next(false);
setTimeout(() => resume$.next(true), 500);
setTimeout(() => resume$.next(false), 5000);

 

here use 

Rx.Observable.empty()

inside switchMap(), it means if code goes to empty(), then the rest of code:

 .do().switchMap()

won‘t run.

 

If just subscribe, it trigger complete function:

var source = Rx.Observable.empty();

var subscription = source.subscribe(
  function (x) {
    console.log(Next: %s, x);
  },
  function (err) {
    console.log(Error: %s, err);
  },
  function () {
    console.log(Completed);
  });
  
// => Completed

 

以上是关于[RxJS] Implement pause and resume feature correctly through RxJS的主要内容,如果未能解决你的问题,请参考以下文章