繁体   English   中英

RxJs 间隔中的新请求

[英]New Request in RxJs interval

我的应用程序中有一个间隔,每 2 分钟从 API 获取一次信息。 这个间隔同时进行 3 个调用,获取一些列表并用它做一些事情。

在这个列表中,有一些项目。 我想删除一项,然后重新调用列表(间隔)以更新新列表并显示它(无需等待间隔时间,基本上,刷新调用)。 但我不知道怎么做。 我尝试创建一个主题并使用.next ('')再次调用间隔(随之而来的错误,ofc)。 我想我遗漏了一些与switchMap和 polling 的操作相关的东西。

    const created$ = this.collections.getMyCollections('created'); // returns Observable<Collection[]>
    const asigns$ = this.collections.getMyCollections('asigns');
    const groups$ = this.collections.getMyCollections('groups');

    /** Interval*/
    let pollInterval = 120000;
    let timer$ = timer(0, pollInterval);


    /** subscriptions */
    this.pollingSubscription  = timer$.pipe(switchMap(() => forkJoin(creates$, asigns$, groups$))).subscribe(([CREATED, ASIGNS, GROUPS]) => {
        /** Some stuff here*/
    });

提前致谢。

您可以从forkJoin切换到forkJoin的 combineLatest:

const created$ = this.collections.getMyCollections("created"); // returns Observable<Collection[]>
const asigns$ = this.collections.getMyCollections("asigns");
const groups$ = this.collections.getMyCollections("groups");

const refresh$ = new BehaviorSubject<"created" | "asigns" | "groups" | "init">(
  "init"
);

/** Interval*/
let pollInterval = 120000;
let timer$ = timer(0, pollInterval);

/** subscriptions */
this.pollingSubscription = timer$
  .pipe(
    switchMap(() =>
      combineLatest(
        refresh$.pipe(
          filter(refreshId => refreshId === 'created' || refreshId === 'init'),
          switchMap(() => created$)
        ),
        refresh$.pipe(
          filter(refreshId => refreshId === 'asigns' || refreshId === 'init'),
          switchMap(() => asigns$)
        ),
        refresh$.pipe(
          filter(refreshId => refreshId === 'groups' || refreshId === 'init'),
          switchMap(() => groups$)
        )
      )
    )
  )
  .subscribe(([CREATED, ASIGNS, GROUPS]) => {
    /** Some stuff here*/
  });

BehaviorSubject将在订阅时发出'init' ,这将触发combineLatest的 3 个 observable。 只要您想刷新其中一个集合,您就可以调用:

this.refresh$.next('created');
// OR
this.refresh$.next('asigns');
// OR
this.refresh$.next('groups');

我没有测试这段代码,这是一般的想法。 我认为您可能需要稍微重写计时器部分,以避免随着时间的推移有多个订阅者。

我对 forkJoin 的偏好是以下模式,如果在 forkJoin 方法之一发出其值后您想要做的事情,它可能会对您有所帮助。

每个 observable 在自己的管道中处理自己的后效,而不是委托给订阅主体。

forkJoin([
  observable1.pipe(
    tap(res1 => this.res1 = res1)
  ),
  observable2.pipe(
    tap(res2 => this.res2 = res2),
    // run additional observable this could be conditional if you need it to be
    switchMap(() => observable2a.run()),
    tap(res2a => this.res2a = res2a)
  ),
  observable3.pipe(
    tap(res3 => this.res = res3)
  )
]).subscribe(() => {
  // clean subscribe body
  // do whatever you need to do now all observables have run  
});

这样做的好处是它将您的可观察依赖关系保持在一起,并防止订阅主体变得一团糟。

有点不清楚删除可能在您的代码中发生的位置,但我认为这种模式可能对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM