Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@princiya
Owner

princiya commented Oct 21, 2017

Output

@princiya

This comment has been minimized.

Show comment
Hide comment
@princiya
Owner

princiya commented Oct 21, 2017

observer pattern

@princiya

This comment has been minimized.

Show comment
Hide comment
@princiya
Owner

princiya commented Oct 22, 2017

observable debugging

@sharifme04

This comment has been minimized.

Show comment
Hide comment
@sharifme04

sharifme04 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

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