[RxJS] Use filter and partition for conditional logic
// begin lesson code
import { fromEvent, partition } from 'rxjs';
import { filter, pluck } from 'rxjs/operators';
const MOVE_SPEED = 20;
let leftPosition = 0;
// elems
const box = document.getElementById('box');
// streams
const click$ = fromEvent(document, 'click');
const xPositionClick$ = click$.pipe(pluck('clientX'));
xPositionClick$.subscribe(xPos => {
/*
* Generally if you have a single if statement in
* you subscribe block, prefer filter instead.
*/
if(xPos < window.innerWidth / 2) {
box.style.left = `${leftPosition -= MOVE_SPEED}px`;
} else {
box.style.left = `${leftPosition += MOVE_SPEED}px`;
}
});
If you found youself doing if/else
it is possible to use partition
operator.
// begin lesson code
import { fromEvent, partition, merge } from 'rxjs';
import { filter, pluck, tap } from 'rxjs/operators';
const MOVE_SPEED = 20;
let leftPosition = 0;
// elems
const box = document.getElementById('box');
// streams
const click$ = fromEvent(document, 'click');
const xPositionClick$ = click$.pipe(pluck('clientX'));
const [ clickLeft$, clickRight$ ] = partition(
xPositionClick$,
xPos => xPos < window.innerWidth / 2
);
const moveLeft = () => {
box.style.left = `${leftPosition -= MOVE_SPEED}px`;
}
const moveRight = () => {
box.style.left = `${leftPosition += MOVE_SPEED}px`;
}
const moveLeft$ = clickLeft$.pipe(tap(moveLeft));
const moveRight$ = clickRight$.pipe(tap(moveRight));
merge(moveLeft$, moveRight$).subscribe()