簡體   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