Mr Speaker


Warning: count(): Parameter must be an array or an object that implements Countable in /home/mrspeak/public_html/wp-content/themes/stuartspeaker/functions.php on line 24

Warning: count(): Parameter must be an array or an object that implements Countable in /home/mrspeak/public_html/wp-content/themes/stuartspeaker/functions.php on line 27

Warning: count(): Parameter must be an array or an object that implements Countable in /home/mrspeak/public_html/wp-content/themes/stuartspeaker/functions.php on line 29

Functions as RxJS Subjects

Here's a nifty trick if you're using RxJS, and want to subscribe to plain ol' function invocation. This is especially useful if you want to use React, and don't want to bind with Rx.Observable.fromEvent with standard DOM event listeners.


import Rx from 'rx';

const RxFuncSubject = () => {
  const subject = Object.assign(
    (...args) => subject.onNext(...args),
    Rx.Observable.prototype,
    Rx.Subject.prototype);

  Rx.Subject.call(subject);

  return subject;
};

export default RxFuncSubject;

We create a regular function that we extend with both Rx.Observable and Rx.Subject (you need to mix in Rx.Observable as this is extended by Rx.Subject internally).

The function passes its arguments along to the internal onNext function: so it can be called as a regular function but still act like a Subject:

const clicker = RxFuncSubject();
clicker.subscribe(() => console.log('clicked!'));
clicker(); // clicked!

Now it can be used in a normal React component, wherever a function call would be expected!

<MyComponent onClick={clicker} />

Warning: count(): Parameter must be an array or an object that implements Countable in /home/mrspeak/public_html/wp-content/themes/stuartspeaker/functions.php on line 33
Captcha! Please type 'radical' here: *
How did you find this thingo? *