rxjs 根据响应中指定的持续时间重复 api 调用 [英] rxjs repeat api call based on duration specified in response

查看:29
本文介绍了rxjs 根据响应中指定的持续时间重复 api 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从具有可变到期时间(在响应中指定)的服务器获取数据.一旦它到期,我需要再次获得它.因此,我想创建一个流来发出异步请求,并在该请求的响应中指定的时间之后重复该请求.

I need to get data from the server that has a variable expiration (specified in the response). Once it expires I need to get it again. So I would like to create a stream that makes an asynchronous request and repeats that request after a time that is specified in the response of that request.

这是我的第一次尝试,但 repeatWhen 无法访问最后一个响应.而不是每 1000 毫秒重复一次,我想根据响应的到期属性来做.

Here is my first attempt but the repeatWhen doesn't have access to the last response. Instead of doing the repeat every 1000ms I would like to do it based on the expiration property on the response.

const { Observable, defer, of } = rxjs;
const { repeatWhen, delay, map, take } = rxjs.operators;

let count = 0;
function api() {
  return of({ data: count++, expiration: Math.random() * 1000 });
}

defer(() => api()).pipe(
  repeatWhen((notification) => notification.pipe(delay(1000))),
  map((response) => response.data),
  take(5)
).subscribe((x) => { console.log(x); });

<script src="https://unpkg.com/rxjs@rc/bundles/rxjs.umd.min.js"></script>

使用 rxjs,如何进行 api 调用并根据上次响应延迟重复调用?

Using rxjs, how can I make an api call and repeat it on a delay based on its last response?

这在技术上做了我想要的,但它有点hacky...所以我想要一个更好的解决方案.

This technically does what I want but it is a bit hacky... so I would like a better solution.

const { Observable, defer, of, BehaviorSubject, timer } = rxjs;
const { repeatWhen, delay, map, take, tap, switchMap } = rxjs.operators;

let count = 0;
function api() {
  return of({ data: count++, expiration: Math.random() * 1000 });
}

const trigger = new BehaviorSubject(0);
trigger.pipe(
  switchMap((expiration) => timer(expiration)),
  switchMap(() => api().pipe(
    tap((response) => { trigger.next(response.expiration); })
  )),
  take(5)
).subscribe((x) => { console.log(x); });

<script src="https://unpkg.com/rxjs@rc/bundles/rxjs.umd.min.js"></script>

推荐答案

这可以使用 .expand() 运算符轻松实现,该运算符用于递归目的.确切的解决方案只有几行:

This can be easily achieved using the .expand() operator, which is meant for recursive purposes. The exact solution is only a few lines:

api()
    .expand(({expiration}) => api().delay(expiration))
    .take(5)
    .subscribe(x=>console.log(x));

这是 JSBin.

这篇关于rxjs 根据响应中指定的持续时间重复 api 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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