Efflam Daniel
Efflam Daniel

Reputation: 283

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

Upvotes: 28

Views: 16150

Answers (2)

Brandon
Brandon

Reputation: 39192

Use pairwise:

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

Upvotes: 42

brokenalarms
brokenalarms

Reputation: 305

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).

Upvotes: 11

Related Questions