[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/elseit 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()

 

 

posted @ 2022-10-22 16:31  Zhentiw  阅读(51)  评论(0)    收藏  举报