Skip to content

Instantly share code, notes, and snippets.

@EloB
Created July 31, 2017 13:15
Show Gist options
  • Save EloB/b6f8f8179161dbd2516275e683b1cea8 to your computer and use it in GitHub Desktop.
Save EloB/b6f8f8179161dbd2516275e683b1cea8 to your computer and use it in GitHub Desktop.
A simple but really powerful abstract Rx React component.
import RxComponent from './RxComponent';
class MyComponent extends RxComponent {
static propTypes = {
// your props type
};
engine() {
const clock$ = Observable.timer(0, 1000);
return this.props$
.combineLatest(
clock$,
({ children, ...props }, clock) => (
<div {...props}>
<div>A timer: {clock}</div>
{children}
</div>
)
);
}
}
import { Component } from 'react';
import { ReplaySubject } from 'rxjs';
class RxComponent extends Component {
state = {
component: null,
};
componentWillMount() {
this.props$.next(this.props);
this.subscription = this.engine().subscribe(component => this.setState({ component }));
}
componentDidMount() {
didMounted$.next();
}
componentWillReceiveProps(props) {
this.props$.next(props);
}
shouldComponentUpdate(nextProps, nextState) {
return this.state.component !== nextState.component;
}
componentWillUnmount() {
this.subscription.unsubscribe();
}
engine() {
throw new Error('Should be implemented');
}
props$ = new ReplaySubject(1);
didMounted$ = new ReplaySubject(1);
render() {
return this.state.component;
}
}
export default RxComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment