I want to swipe between pages in angular using native events and rxjs. I found this and changed my code to work with rxjs:
ngAfterViewInit(): void {
fromEvent<TouchEvent>(document, 'touchstart')
.pipe(
switchMap(() =>
fromEvent<TouchEvent>(document, 'touchmove').pipe(
takeUntil(fromEvent(document, 'touchend')),
pairwise()
)
)
)
.subscribe(([touchstartEvent, touchendEvent]) => {
const xDiff =
touchstartEvent.touches[0].clientX - touchendEvent.touches[0].clientX;
console.log(xDiff);
if (Math.abs(xDiff) < 0.3 * document.body.clientWidth) {
return;
}
if (xDiff > 0) {
console.log('right swipe');
} else {
console.log('left swipe');
}
});
}
However my function in subscribe is called multiple times, which means my swipe is never executed because my treshhold 0.3 * document.body.clientWidth
is never met. For debugging I added the following code:
fromEvent(document, 'touchend').subscribe((e) => {
console.log('test2');
});
Then my console output is something like this, showing takeUntil
not working as expected:
test -24.941162109375
test -8
test -9.41180419921875
test -8.4705810546875
test -9.88232421875
test2
What am I missing here?