• withLatestFrom
    • 签名: withLatestFrom(other: Observable, project: Function): Observable
  • 还提供另一个 observable 的最新值。
    • 示例
      • 示例 1: 发出频率更快的第二个 source 的最新值
      • 示例 2: 第二个 source 发出频率更慢一些
  • 相关食谱
  • 其他资源

    withLatestFrom

    签名: withLatestFrom(other: Observable, project: Function): Observable

    还提供另一个 observable 的最新值。


    :bulb: 如果你希望每当任意 observable 发出值时各个 observable 的最新值,请尝试 combinelatest!


    withLatestFrom - 图2

    示例

    示例 1: 发出频率更快的第二个 source 的最新值

    ( StackBlitz |
    jsBin |
    jsFiddle )

    1. import { withLatestFrom, map } from 'rxjs/operators';
    2. import { interval } from 'rxjs/observable/interval';
    3. // 每5秒发出值
    4. const source = interval(5000);
    5. // 每1秒发出值
    6. const secondSource = interval(1000);
    7. const example = source.pipe(
    8. withLatestFrom(secondSource),
    9. map(([first, second]) => {
    10. return `First Source (5s): ${first} Second Source (1s): ${second}`;
    11. })
    12. );
    13. /*
    14. 输出:
    15. "First Source (5s): 0 Second Source (1s): 4"
    16. "First Source (5s): 1 Second Source (1s): 9"
    17. "First Source (5s): 2 Second Source (1s): 14"
    18. ...
    19. */
    20. const subscribe = example.subscribe(val => console.log(val));
    示例 2: 第二个 source 发出频率更慢一些

    ( StackBlitz |
    jsBin |
    jsFiddle )

    1. import { withLatestFrom, map } from 'rxjs/operators';
    2. import { interval } from 'rxjs/observable/interval';
    3. // 每5秒发出值
    4. const source = interval(5000);
    5. // 每1秒发出值
    6. const secondSource = interval(1000);
    7. // withLatestFrom 的 observable 比源 observable 慢
    8. const example = secondSource.pipe(
    9. // 两个 observable 在发出值前要确保至少都有1个值 (需要等待5秒)
    10. withLatestFrom(source),
    11. map(([first, second]) => {
    12. return `Source (1s): ${first} Latest From (5s): ${second}`;
    13. })
    14. );
    15. /*
    16. "Source (1s): 4 Latest From (5s): 0"
    17. "Source (1s): 5 Latest From (5s): 0"
    18. "Source (1s): 6 Latest From (5s): 0"
    19. ...
    20. */
    21. const subscribe = example.subscribe(val => console.log(val));

    相关食谱

    • 进度条
    • 游戏循环

    其他资源

    • withLatestFrom :newspaper: - 官方文档
    • 组合操作符: withLatestFrom :video_camera: :dollar: - André Staltz

    :file_folder: 源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/withLatestFrom.ts