javascript 获取 RxJS Observable 的最后两个值之间的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31298683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:36:41  来源:igfitidea点击:

Get difference between last two values of an RxJS Observable

javascriptrxjs

提问by Efflam Daniel

I have an observable tracking the scroll position

我有一个可观察的跟踪滚动位置

 const scroll = Observable
  .fromEvent(document, 'scroll')
  .map(e => window.pageYOffset)
  .startWith(0)

I would like to have a second observable tracking the scroll delta (newScroll - lastScroll)

我想要第二个 observable 跟踪滚动增量 (newScroll - lastScroll)

const scrollDelta = scroll
  // ???
  .subscribe(delta => console.log('delta:', delta) )

How to implement something like this? I've tried with scan with no success. Thx

如何实现这样的事情?我试过扫描但没有成功。谢谢

回答by Brandon

Use pairwise:

成对使用:

scroll
    .pairwise()
    .map([a, b] => b - a);

回答by brokenalarms

Old question, but to add info for RxJS version 5, where the API surface has changed somewhat and it took me some time to find the answer: the equivalent to pairwisewould be bufferWithCount(2,1)(v4) or bufferCount(2,1)(v5).

老问题,但要加信息的RxJS 5版本,其中API面已经有所改变,我花了一些时间来找到答案:相当于pairwisebufferWithCount(2,1)(V4)或bufferCount(2,1)(V5)。