rxjs:定期执行一些操作,之间有特定的延迟

Sas*_*asa 4 reactive-programming rxjs angular

客户端应用程序将请求发送到服务器,这可能需要很长时间才能完成。一旦请求完成或失败,客户应该等待的时间(即10秒)一段时间,然后重新发送请求。

当前的工作解决方案是这样的:

appRequest = new Subject();

ngOnInit(): void {
  this.appRequest.delay(10000).subscribe(() => this.refresh());
  this.refresh();
}

refresh() {
  this.api.getApplications().subscribe(a => {
      this.updateApplications(a);
      this.appRequest.next();
    },() => this.appRequest.next()
  );
}
Run Code Online (Sandbox Code Playgroud)

有没有更优雅的解决方案呢?

编辑:

我可以使用与定期计时器,但我不想除非先前请求已经完成发送新的请求。仅在先前的请求完成后,我才需要等待10秒钟,然后再次发送请求。这应该无限期地重复。

getApplications()函数由swagger生成,并且在内部使用angular的http客户端库。目前的看法是,除非你订阅Observable的返回getApplications(),也不会发送请求到服务器。

Ric*_*sen 5

repeatWhen()操作似乎专为这一点,但还缺乏在rxjs味道实例和文档。

这是RxJava的文档(说明也适用于RxJs)。RxJava的repeatWhen和retryWhen解释说

采用
轮询定期使用repeatWhen +延迟数据:
source.repeatWhen(completed => completed.delay(5000))

您的版本可能是

stopRequesting = new Subject();

ngOnInit() {
  this.api.getApplications()
    .repeatWhen(completed => completed.delay(10000))
    .takeUntil(stopRequesting)
    .subscribe(a => this.updateApplications(a))
} 

ngOnDestroy() {
  this.stopRequesting.next(true);
}
Run Code Online (Sandbox Code Playgroud)

演示版

// log to html output
log = function(x) { document.write(x + "<br />"); };

const stop = new Rx.Subject();

Rx.Observable.interval(500)
  .take(2)
  .repeatWhen(completed => completed.delay(1000))
  .takeUntil(stop)
  .subscribe(
    x => log(`Next: ${x}`),
    err => log(`Error: ${err}`),
    () => log('Completed')
  );

setTimeout(() => stop.next(true), 10000)
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>
Run Code Online (Sandbox Code Playgroud)


Laz*_*vić 0

您正在寻找interval接线员

从上面的链接:

// emit value in sequence every 1 second
const source = Rx.Observable.interval(1000);
// output: 0,1,2,3,4,5....
const subscribe = source.subscribe(val => console.log(val));
Run Code Online (Sandbox Code Playgroud)

  • 这种方法的问题在于它不等待先前的请求完成。我需要它等待上一个请求完成,然后等待 10 秒,然后发出新请求。 (7认同)