RxJs达到期望值之前的可观察间隔 [英] RxJs Observable interval until reached desired value

查看:99
本文介绍了RxJs达到期望值之前的可观察间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想轮询更改,并且当达到所需值时,Observable应该完成(或等到超时).现在,我使用过滤器,该过滤器可以很好地等待直到达到所需的值.但是我希望Observable在等待该值的同时推送事件.

I want to poll for changes and when a desired value is reached the Observable should complete (or wait until timeout). Right now I use the filter which works fine to wait until the desired value is reached. But I want the Observable to push events while waiting for this value.

例如,我等待状态成功",直到状态更改为成功",状态测试"从我的服务中返回.但是由于过滤器正在等待成功",所以测试"再也不会返回.

For example, I wait for the status 'success' and until the status changes to 'success' the status 'testing' is returned from my service. But since the filter is waiting for 'success', 'testing' never returns.

我现在的代码:

return Observable
  .interval(this.POLL_TIMEOUT)
  .flatMap(() => this.getSingleProjectStatus(projectId, repoName))
  .filter(data => this.finishedStatus(data.status))
  .take(1)
  .timeout(this.MAX_TIMEOUT, Observable.throw(new Error('Timeout')));

推荐答案

您可能想要请注意,上述操作将所有 except 都作为最后一个事件,如果您也想要最后一个事件,则需要更加棘手.

Note the above takes all except the last event, if you want the last event too you'll need to be a little trickier.

  const source = Observable.interval(this.POLL_TIMEOUT)
    .flatMap(() => this.getSingleProjectStatus(projectId, repoName))
    .share();

  source
    .takeUntil(source.filter(data => this.finishedStatus(data.status)))
    .timeout(this.MAX_TIMEOUT, Observable.throw(new Error('Timeout'));

在这种情况下,您要获取所有结果,直到发出另一个Observable为止,在这种情况下,另一个Observable只是经过过滤的source,使其仅发出成功事件.

In this case you are taking all the results until another Observable emits, the other Observable in this case is simply the source filtered such that it only emits success events.

JsBin: http://jsbin.com/sojosuhune/edit?html, js,控制台,输出

这篇关于RxJs达到期望值之前的可观察间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆