Skip to content

Instantly share code, notes, and snippets.

@princiya
Created October 21, 2017 07:50
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 princiya/fbf227d6d4f68deaa5e0689351b01093 to your computer and use it in GitHub Desktop.
Save princiya/fbf227d6d4f68deaa5e0689351b01093 to your computer and use it in GitHub Desktop.
Reusable React component to render the output of an observable
import React, { Component } from 'react';
import Rx from 'rxjs/Rx';
import './App.css';
import Observable from './components/Observable';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<h2>React & Observables</h2>
</div>
<Observable observable={
Rx.Observable.interval(1000).startWith(-1).map((i) => i + 2)
.map((i) =>
<div> {i}
<Observable observable={
Rx.Observable
.interval(1000 / (i + 1)).startWith(-1)
.map((j) => '-'.repeat(j + 1))
} />
</div>
)}
/>
</div>
);
}
}
export default App;
import React, { Component } from 'react';
class Observable extends Component {
constructor(props) {
super(props);
this.state = {
x: null
};
}
componentDidMount() {
this.props.observable.subscribe(
(x) => {
this.setState({ x });
},
e => console.log('onError: %s', e),
() => console.log('onCompleted'))
}
render() {
return (
<div>
{this.state.x}
{this.props.children}
</div>
);
}
}
export default Observable;
@princiya
Copy link
Author

Output

@princiya
Copy link
Author

observer pattern

@princiya
Copy link
Author

observable debugging

@sharifme04
Copy link

sharifme04 commented Oct 14, 2018

Could you please tell me , If you want to do unsubscribe, how will you do from ComponentWillUnmount? I tried but I see it does not call ComponentWillUnmount. I am not expert, I am learning and working. Also your code is not work anymore . Kindly check that

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment