user2999287 user2999287 - 1 month ago 17
Javascript Question

Rx js how to reuse operators

I am using Rx, and I have two clicks streams that use the same operators.
How can I extract the same portion and reuse it?

let gender$ = Rx.Observable.fromEvent(gender, 'click').map(e => e.target).filter(t => t.nodeName === "LI").map(li => li.textContent.trim())

let type$ = Rx.Observable.fromEvent(type, 'click').map(e => e.target).filter(t => t.nodeName === "LI").map(li => li.textContent.trim())

let combine$ = Rx.Observable.combineLatest(
gender$,
type$
)


I want to extract this:

.map(e => e.target).filter(t => t.nodeName === "LI").map(li => li.textContent.trim())

Answer
const getTextFromLis = stream$ => stream$.map(e => e.target).filter(t => t.nodeName === "LI").map(li => li.textContent.trim());

let gender$ = getTextFromLis(Rx.Observable.fromEvent(gender, 'click'));

The chaining part of Rx means that calling .map() or .filter() will get you a new stream, which you can pass and return to/from functions.

Comments