Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

javascript - RxJS. Combine observables that emit less then 1 second apart

There are two observables that may be emiting together or separately: stream1 and stream2. I need my subscription to fire only if stream2 fires less then 1 second after stream1 does.
Any way to achieve that with RxJS?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a timestamp and withLatestFrom to decide which values to emit Here I just filter such that only values that meet your condition pass through.

stream2.pipe(
  timestamp(),
  withLatestFrom(stream1.pipe(
    timestamp(),
    startWith({timestamp: 0, value: null})
  )),
  filter(([s2, s1]) => s2.timestamp - s1.timestamp < 1000),
  map(([s2, s1]) => ({
    stream1: s1.value,
    stream2: s2.value
  }))
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...