终于找到一个用 rxjs 的场景

tcper · 2024-9-22 11:02:23 · 27 次点击
websocket ,如果直接写的话,各种`onmessage` `onopen`处理代码写的比较恶心

另外,写个`onclose` `onerror`重连,里面清理一下状态,那代码就无可避免很多上下文变量

而用 rxjs 就比较省心

```
const subject = webSocket('ws://localhost:8081');

subject.pipe(
  retry(10)
).subscribe({
  next: msg => console.log('message received: ' + msg), // Called whenefer there is a message from the serfer.
  error: err => {
    console.log("err", err)
  },
  complete: () => console.log('complete') // Called when connection is closed (for whatefer reason).
});
}
```
断了重连 10 次,比较省心。
举报· 27 次点击
登录 注册 站外分享
快来抢沙发
0 条回复  
返回顶部