Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use RxJs distinctUntilChanged?

Tags:

I'm getting started with RxJs (using the v5 beta), but somehow I can't figure out how to work with distinctUntilChanged. The output from the code below if I run it in babel-node is

[ 'a', 1 ] { key: 'a', state: 1 } Next:  { value: 42 } Completed 

That is not what I would expect. Why is only one entry passing distinctUntilChanged? I would expect the output to be

[ 'a', 1 ] [ 'a', 0 ] [ 'a', 1 ] { key: 'a', state: 1 } { key: 'a', state: 2 } { key: 'a', state: 0 } { key: 'a', state: 1 } Next:  { value: 42 } Next:  { value: 24 } Completed 

Here's the code

import {Observable} from 'rxjs'  Observable.of(['a', 1], ['a', 1], ['a', 0], ['a', 1])   .distinctUntilChanged(x => x[1])   .subscribe(x => console.log(x))  Observable.of({key: 'a', state: 1}, {key: 'a', state: 2}, {key: 'a', state: 0}, {key: 'a', state: 1})   .distinctUntilChanged(x => x.state)   .subscribe(x => console.log(x))  Observable.of({value: 42}, {value: 42}, {value: 24}, {value: 24})   .distinctUntilChanged(x => x.value)   .subscribe(     function (x) {       console.log('Next: ', x)     },     function (err) {       console.log('Error: ' + err)     },     function () {       console.log('Completed')     }   ) 

The links in the v5 docs for these functions appear to be dead

------ edit -----

Some additional debugging:

Observable.of(['a', 1], ['a', 1], ['a', 0], ['a', 1])   .do(x => console.log('before', x))   .distinctUntilChanged(x => x[1])   .do(x => console.log('after', x))   .subscribe(x => console.log(x)) 

output:

before [ 'a', 1 ] after [ 'a', 1 ] [ 'a', 1 ] before [ 'a', 1 ] before [ 'a', 0 ] before [ 'a', 1 ] 
like image 436
Thijs Koerselman Avatar asked Mar 28 '16 22:03

Thijs Koerselman


People also ask

What is scan in RXJS?

scan((total, n) => total + n), // Get the average by dividing the sum by the total number. // received so var (which is 1 more than the zero-based index). map((sum, index) => sum / (index + 1)) )

What is pipe operator in RXJS?

A Pipeable Operator is a function that takes an Observable as its input and returns another Observable. It is a pure operation: the previous Observable stays unmodified. A Pipeable Operator is essentially a pure function which takes one Observable as input and generates another Observable as output.


1 Answers

I got an answer here. Basically the function signature changed from (key selector, comparator) to (comparator, key selector).

This is how the example is done in v5:

Observable.of(['a', 1], ['a', 1], ['a', 0], ['a', 1])   .distinctUntilChanged(null, x => x[1])   .subscribe(x => console.log(x)) 
like image 114
Thijs Koerselman Avatar answered Oct 07 '22 09:10

Thijs Koerselman