前言
在websocket开发时,socket.io无疑是一个非常好用的库,但是socket.io本身的api全部是基于回调的, 使得我们在日常开发中,尤其将socket抽离和状态管理的action放一起, 组件只通过触发socket这种方式开发时, 增加了很多的不方便。
经过思考及对比,发现rxjs在做这种异步响应式编程的时候有得天独厚的优势,且能满足我们的很多想象空间。
国际惯例,先上github
实现
首先肯定是借助rxjs最主要的两个api, fromEvent将on方法封装。Observable.create将emit方法封装。暂时只把常用的这两个方法封装,后续如果发现不够用再对其他api进行封装
话不多说,直接上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import io from "socket.io-client"; import { fromEvent, Observable } from 'rxjs'
export default class RxSocket { constructor(url, option) { this.socket = io.connect(url, option) }
on(eventName) { return fromEvent(this.socket, eventName) }
emit(type, ...data) { return Observable.create(obs => { this.socket.emit(type, ...data, (e) => { obs.next(e) }) }) } }
|
使用
如果rxjs使用比较熟悉,或者有接触过的同学可能看到实现就已经知道怎么用了, 因为这两个方法返回的都是Observable可观察对象 ,直接实例化以后,订阅实例方法就可以。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import React, { Component } from 'react';
import RxSocket from './rx.socket'
export default class Chat extends Component { constructor() { super() this.socket = new RxSocket('http://localhost:3000')
this.state = { msg: '' } }
componentDidMount() { this.socket.on('hello').subscribe((e) => { this.setState({ msg: e }) }) }
sendMsg() { this.socket.emit('from', 'react').subscribe((e) => {console.log(e)}) }
render() { return ( <div> <p>{this.state.msg}</p> <button onClick={this.sendMsg.bind(this)}>发送消息</button> </div> ) } }
|