dmuensterer
dmuensterer

Reputation: 1885

RxJS get before/after emission values of Observable

I'd like to calculate a difference between emissions of a single Observable.

Is there a way to get both the current and previous emission of an Observable if it emits a new value? I'd like something like this:

ob$.subscribe(val => {
  console.log(val)
  // First emission: [1,2,3]

  // Second emission: [1,2,3,4]

  console.log(arrayDifference(before, after)) // [4]
})

How would I go about that? Do I need to store every emission in an upper-scope variable or is there a fancy RxJS way to do this?

Upvotes: 4

Views: 295

Answers (3)

emmanuel agarry
emmanuel agarry

Reputation: 355

Use the scan operator to check the previous value

   const arrayDifference = (before, after) => {
    // Immlement the fuction here
    
    const difference = .........
    return difference
    }
    
    
    ob$.pipe(scan((before,after) => arrayDifference(before,after), [])).subscribe(val =>  console.log(val))

This should work

Upvotes: 2

GBra 4.669
GBra 4.669

Reputation: 1679

I would use startWith and pairwise()

 const randomObservable = of('observableString')
  .pipe(startWith('defaultString'), pairwise())
  .subscribe(arrayOfStrings => console.log(arrayOfStrings[0], arrayOfStrings[1]));

The code above will console log: 'defaultString', 'observableString'.

Upvotes: 0

martin
martin

Reputation: 96899

You can do that with bufferCount operator which is very modular:

bufferCount(2, 1)

It'll create a new buffer of size 2 after every 1 emission from source.

Alternativelly, there also pairwise() operator that does exactly the same thing .

Upvotes: 2

Related Questions