RxJs only take the first value of certain type and skip the rest until a different type of value

937 views Asked by At

I have a scenario where I want to take only the first value of a certain type and then take the next different value which is of a different type.

To understand let's consider the following:

of(1,1,1,1,2,3,4)
.pipe(
    // some operators
)
.subscribe(val => console.log(val);

I am only interested in the output 1,2,3,4

note that the 1 in the output should be the first value in the source and not the one before 2.

how do I achieve this using rxjs operators?

2

There are 2 answers

0
Jiajun On

So given 111223111

If you want to get 123 use distinct operator

If you want to get 1231 use distinctUntilChanged operator

1
evilstiefel On

The operator you're looking for is called distinctUntilChanged(), like so:

of(1,1,1,1,2,3,4).pipe(
    distinctUntilChanged()
).subscribe(val => console.log(val));

This would result in 1, 2, 3, 4. Do note that any other value that has previously occured, will occur again, so it's not like a DISTINCT in SQL (e.g. 1,1,2,3,4,1 would produce output 1, 2, 3, 4, 1).