V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
tcper
V2EX  ›  前端开发

终于找到一个用 rxjs 的场景

  •  
  •   tcper · 24 天前 · 925 次点击

    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 whenever there is a message from the server.
      error: err => {
        console.log("err", err)
      }, 
      complete: () => console.log('complete') // Called when connection is closed (for whatever reason).
     });
    }
    

    断了重连 10 次,比较省心。

    2 条回复    2024-10-12 09:48:51 +08:00
    NerdHND
        1
    NerdHND  
       4 天前
    前几天还在沉迷 rxjs, 但是尝试几天发现真的可以用的地方好少, 大部分情况没这么复杂的请求. 以后做 ws webrtc 看看不知道有没有场景.
    tcper
        2
    tcper  
    OP
       4 天前
    @NerdHND ws, sse 都比较适合。
    别的场景要看你对 rxjs 的熟练程度,不熟练是不会想到用 rxjs 。
    另外 rxjs 的异步怎么和 react/vue 变量的同步,和状态管理的同步也是个问题。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3229 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 11:27 · PVG 19:27 · LAX 04:27 · JFK 07:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.