簡體   English   中英

當多個可觀察對象同時發出值時,combineLatest RxJS 運算符如何工作?

[英]How does combineLatest RxJS operator works when multiple observables emit values at the same time?

RxJS 文檔指出

combineLatest組合多個 Observable 以創建一個 Observable,其值是根據每個輸入 Observable 的最新值計算得出的。

我想了解當多個 observables 同時發出值時combineLatest是如何工作的?

如果我們看下面的代碼

import 'zone.js/dist/zone';
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import { timer, take, combineLatest } from 'rxjs';

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule],
  template: `Hello`,
})
export class App {
  name = 'Angular';

  constructor() {
    const a$ = timer(0, 1000).pipe(take(5)); //Emit values after each second (total 5 values)

    const b$ = timer(0, 4000).pipe(take(5)); //Emit values after every 4 seconds (total 5 values)

    //Marble Diagram
    
    //0 1 2 3 4
    //0       1       2       3       4

    const result$ = combineLatest(a$, b$);

    result$.subscribe((val) => console.log(val));
  }
}

bootstrapApplication(App);

output 如下Output在上面的 output 中,在第 4 秒result$ observable 同時輸出值 [4,0] 和 [4,1]。

我的問題是,為什么它不只打印 [4,1],因為 combineLatest 帶來了最新值,“4”是可觀察a$的最新值,而“1”是第 4 秒可觀察b$的最新值.

鏈接到演示

提前致謝!

在每個源發出至少一個值后,只要它的任何源可觀察量發出, combineLatest就會發出。

即使兩個 observables“同時”發射(我假設你真的是在同一個事件循環中), combineLatest也會發射兩次。

如果你想防止在同一個事件循環中發生發射,你可以使用debounceTime(0)

result$ = combineLatest(a$, b$).pipe(debounceTime(0));

你可以像這樣使用它:

import 'zone.js/dist/zone';
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import { timer, take, withLatestFrom } from 'rxjs';

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule],
  template: `Hello`,
})
export class App {
  name = 'Angular';

  constructor() {
    const a$ = timer(0, 1000).pipe(take(5)); //Emit values after each second (total 5 values)

    const b$ = timer(0, 4000).pipe(take(5)); //Emit values after every 4 seconds (total 5 values)

    const result$ = a$.pipe(withLatestFrom(b$, (a, b) => [a, b]));

    result$.subscribe((val) => console.log(val));
  }
}

bootstrapApplication(App);

https://stackblitz.com/edit/angular-gsyobe?file=src/main.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM