Rxjs, fromEvent to handle multiple events

What is the best way to handle multiple events on the same DOM node in rxjs 5.1?

fromEvent($element, 'event_name')but I can only specify one event at a time.

I need to handle events scroll wheel touchmove touchend.

+11
source share
3 answers

Note: this is for RxJS v5. See the bottom of this answer for the v6 equivalent.


You can use the function to combine several observed streams into one stream: Rx.Observable.merge

// First, create a separate observable for each event:
const scrollEvents$    = Observable.fromEvent($element, 'scroll');
const wheelEvents$     = Observable.fromEvent($element, 'wheel');
const touchMoveEvents$ = Observable.fromEvent($element, 'touchmove');
const touchEndEvents$  = Observable.fromEvent($element, 'touchend');

// Then, merge all observables into one single stream:
const allEvents$ = Observable.merge(
    scrollEvents$,
    wheelEvents$,
    touchMoveEvents$,
    touchEndEvents$
);

, , , . , - :

const events = [
    'scroll',
    'wheel',
    'touchmove',
    'touchend',
];

const eventStreams = events.map((ev) => Observable.fromEvent($element, ev));
const allEvents$ = Observable.merge(...eventStreams);

:

const subscription = allEvents$.subscribe((event) => {
    // do something with event...
    // event may be of any type present in the events array.
});

RxJS v6

RxJS 6 merge fromEvent v5, :

import { fromEvent, merge } from 'rxjs';

const scrollEvents = fromEvent($element, 'scroll');
// creating other input observables...

const allEvents$ = merge(
    scrollEvents$,
    wheelEvents$,
    touchMoveEvents$,
    touchEndEvents$
);
+31

:

fromEvents(dom, "scroll", "wheel", "touch", "etc...");
function fromEvents(dom, ...eventNames: string[]) {
    return eventNames.reduce(
        (prev, name) => Rx.merge(prev, fromEvent(dom, name)),
        Rx.empty()
    );
}
+2

RxJs

const events = ['scroll', 'resize', 'orientationchange']
from(events)
  .pipe(
    mergeMap(event => fromEvent($element, event))
  )
  .subscribe(
    event => // Do something with the event here
  )
+2

Source: https://habr.com/ru/post/1682980/


All Articles