Created
December 14, 2018 19:04
-
-
Save dezfowler/1532156a80598dbf8fca86a1b3ecb916 to your computer and use it in GitHub Desktop.
Observable Clock.jsx
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
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