Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 704
Efflam Daniel Avatar asked Jul 08 '15 16:07

Efflam Daniel


2 Answers

Use pairwise:

scroll
    .pairwise()
    .map(([a, b]) => b - a);
like image 150
Brandon Avatar answered Nov 15 '22 21:11

Brandon


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 pairwise would be bufferWithCount(2,1) (v4) or bufferCount(2,1) (v5).

like image 24
brokenalarms Avatar answered Nov 15 '22 20:11

brokenalarms