Created
July 31, 2017 13:15
-
-
Save EloB/b6f8f8179161dbd2516275e683b1cea8 to your computer and use it in GitHub Desktop.
A simple but really powerful abstract Rx React component.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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