Skip to content

Instantly share code, notes, and snippets.

@dezfowler
Created December 14, 2018 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dezfowler/1532156a80598dbf8fca86a1b3ecb916 to your computer and use it in GitHub Desktop.
Save dezfowler/1532156a80598dbf8fca86a1b3ecb916 to your computer and use it in GitHub Desktop.
Observable Clock.jsx
class Clock extends React.Component {
constructor(props) {
super(props);
console.log('new');
this.state = { time: new Date() };
}
componentDidMount() {
this.propsChangeSubject = new Subject();
this.subscription = this.propsChangeSubject
.pipe(
switchMap(running => running ? interval(0, 1000) : empty()),
tap(_ => this.setState({ time: new Date() }))
)
.subscribe();
this.propsChangeSubject.next(this.props.running);
}
componentWillUnmount() {
if (this.subscription) {
this.subscription.dispose();
}
}
componentDidUpdate(prevProps) {
if (this.props.running != prevProps.running) {
this.propsChangeSubject.next(this.props.running);
}
}
render() {
return (<span className="time">{this.state.time.toLocaleTimeString()}</span>);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment