0

I'm having trouble getting the below code to work.

I can get the data using just SocketIO but not with RxJS 6.

class App extends Component {
  constructor(props){
    super(props);
  }
    state = {
      clusterdata: {}
    }
  componentDidMount(){
    const socket = io('http://localhost:5000',{
      path: '/stream',
      transports: ['websocket']
    });
    socket.emit('json', 'my-ecs-cluster');
      const clusterStream = Observable.create(observer => {
        socket.on('connect', socket => {
            console.log(socket);
          socket.on('json', data => {
            observer.next(data)
          })
      })
        this.clusterStreamObserver = clusterStream.subscribe(this.setClusterData.bind(this));
    })

... the setState part

setClusterData(clusterdata){
     if (!clusterdata || clusterdata.length === 0) {
       return;
       this.setState({clusterdata: clusterdata});
     }
  }

... the render part

render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          {JSON.stringify(this.state.clusterdata)}

        </p>
      </div>
    );
  }
}

export default App;
1
  • you can find all details on how to use Observables over socketIO here in this article or here in this other article Commented Jul 23, 2018 at 14:14

1 Answer 1

2

You can try to create an Observable by the following way:

const socket = io('http://localhost:5000',{ path: '/stream', transports: ['websocket'] });

const connection$ = Rx.Observable.fromEvent(socket, 'connect');

connection$.subscribe();

Sign up to request clarification or add additional context in comments.

1 Comment

This works, thanks: socket.on('connect', sock => { socket.emit('json', 'my-ecs-cluster'); const clusterStream = fromEvent(socket, 'json') this.clusterStreamObserver = clusterStream.subscribe(this.setClusterData.bind(this)); }) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.