Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs pairwise is emitting duplicate values

I'm trying to create two scroll event observable for both scroll direction vertical and horizontal.

I tried using pairwise() and bufferCount(2,1) operators to filter vertical scroll event from the horizontal one, but the problem is with getting duplicate values for prev.scrollTop and curr.scrollTop

import { Component, ViewChild, AfterViewInit, ElementRef } from '@angular/core';
import { fromEvent } from 'rxjs';
import { pairwise, tap, filter } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  @ViewChild('scrollable', {static: false}) scrollable: ElementRef;


  ngAfterViewInit() {

    fromEvent(this.scrollable.nativeElement, 'scroll').pipe(
      pairwise(),
      tap(([prev, curr]) => console.log(prev.target.scrollTop, curr.target.scrollTop)),
      filter(([prev, curr]) => prev.target.scrollTop !== curr.target.scrollTop),
      tap((e) => console.log(e)) // <=    Never reached
    ).subscribe();

  }

}

Any ideas?

stackblitz reproduction

like image 604
Murhaf Sousli Avatar asked Dec 31 '25 03:12

Murhaf Sousli


1 Answers

that's because you pairwised the nativeElement, which is always referencing the same object. So basically you have to pluck your desire primitive value.

  fromEvent(this.scrollable.nativeElement, 'scroll').pipe(
      pluck('target','scrollTop'),
      pairwise(),
      tap(([prev, curr]) => console.log(prev,curr)),
      filter(([prev, curr]) => prev!== curr),
      tap((e) => console.log(e)) // <=    Never reached
    ).subscribe();
like image 78
Fan Cheung Avatar answered Jan 05 '26 00:01

Fan Cheung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!