文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
withLatestFrom
withLatestFrom
函数签名: withLatestFrom(other: Observable, project: Function): Observable
还提供另一个 observable 的最新值。
如果你希望每当任意 observable 发出值时各个 observable 的最新值,请尝试 combinelatest!
示例
示例 1: 发出频率更快的第二个 source 的最新值
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { withLatestFrom, map } from 'rxjs/operators';
import { interval } from 'rxjs';
// 每5秒发出值
const source = interval(5000);
// 每1秒发出值
const secondSource = interval(1000);
const example = source.pipe(
withLatestFrom(secondSource),
map(([first, second]) => {
return `First Source (5s): ${first} Second Source (1s): ${second}`;
})
);
/*
输出:
"First Source (5s): 0 Second Source (1s): 4"
"First Source (5s): 1 Second Source (1s): 9"
"First Source (5s): 2 Second Source (1s): 14"
...
*/
const subscribe = example.subscribe(val => console.log(val));
示例 2: 第二个 source 发出频率更慢一些
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { withLatestFrom, map } from 'rxjs/operators';
import { interval } from 'rxjs';
// 每5秒发出值
const source = interval(5000);
// 每1秒发出值
const secondSource = interval(1000);
// withLatestFrom 的 observable 比源 observable 慢
const example = secondSource.pipe(
// 两个 observable 在发出值前要确保至少都有1个值 (需要等待5秒)
withLatestFrom(source),
map(([first, second]) => {
return `Source (1s): ${first} Latest From (5s): ${second}`;
})
);
/*
"Source (1s): 4 Latest From (5s): 0"
"Source (1s): 5 Latest From (5s): 0"
"Source (1s): 6 Latest From (5s): 0"
...
*/
const subscribe = example.subscribe(val => console.log(val));
相关食谱
其他资源
- withLatestFrom :newspaper: - 官方文档
- 组合操作符: withLatestFrom :video_camera: :dollar: - André Staltz
源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/withLatestFrom.ts
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论