Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

My goto example for RxJS are event handlers. Heres an example that implements drag-and-drop (for which the vanillajs / d3js versions aren't nearly as pretty)

It basically translates to

1. Wait for a mousedown event

2. Start listening for mousemove events

2a. On each mousemove event, do something

2b. When a mouseup event occurs, stop listening for mousemoves and return to 1.

    import { fromEvent } from 'rxjs';
    import { exhaustMap, takeUntil, tap } from 'rxjs/operators';

    const el = document.querySelector('body');
    const mousedown$ = fromEvent<MouseEvent>(el, 'mousedown');
    const mousemove$ = fromEvent<MouseEvent>(document, 'mousemove');
    const mouseup$ = fromEvent<MouseEvent>(document, 'mouseup');

    mousedown$.pipe(
      exhaustMap(mousedownEvent => mousemove$.pipe(takeUntil(mouseup$))),
      tap(mousemoveEvent => {
        console.log('mousemove')
      })
    ).subscribe();
https://stackblitz.com/edit/drag-and-drop-rx-rvdkzv?file=ind...

---

More specifically I've found RxJS makes simple one-off calls (eg API fetches) ceremoniously painful (do I need to unsubscribe? do I get the value sync-ly or async?), but anything that involves multiple values (eg websockets, polling, event handlers) gets much cleaner.

My biggest complaint with RxJS is probably the dev experience though. It makes call stacks / the debugger useless so you have to get comfortable with console.log's everywhere. Which is one of the reasons I avoid chaining observables and filter()s in general.



Hmm I agree with call stacks, but the debugger is doing fine




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: