简体   繁体   中英

Get difference between last two values of an RxJS Observable

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)

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

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

Use pairwise :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM