• 请不要在回答技术问题时复制粘贴 AI 生成的内容
shadeofgod
V2EX  ›  程序员

撸了个轮子解决 electron 跨进程共享状态的需求

  •  
  •   shadeofgod ·
    zoubingwu · Feb 18, 2020 · 2153 views
    This topic created in 2291 days ago, the information mentioned may be changed or developed.

    开门直接放链接吧 https://github.com/shadeofgod/electron-shared-state

    electron 那个 ipc 蛋疼的一批,有人做了个 electron-redux 不过太麻烦了,不是很好用,很多时候需要共享的只是一小块状态,完全没必要上 redux。搜了下也没找到啥好方案,正好最近写代码时间比较充裕干脆自己撸了个轮子。

    代码很简单,也就 100 来行 ts,主要是基于 immer 封装了一下,直接修改一个对象,其他的进程也会触发修改。因为只会通过 ipc 发送 patch 而不是整个完整对象,所以性能还是可以的。

    API 超级简单,就一个函数,输入是需要共享的状态,输出是个 object,上面三个方法,getState/setState/subscribe, 没了。

    // shared
    export const initialState = 0;
    
    // renderer
    const sharedStore = createSharedStore(initialState);
    sharedStore.subscribe(state => {
      console.log(state);
    });
    
    setTimeout(() => {
      sharedStore.setState(state => {
        state = state + 1;
      });
    }, 2000);
    
    // main
    const sharedStore = createSharedStore(initialState);
    sharedStore.subscribe(state => {
      console.log(state);
    });
    
    // both main and renderer will print the state after two seconds.
    

    欢迎 pr/issue/star

    shadeofgod
        1
    shadeofgod  
    OP
       Feb 18, 2020
    顺便再给另一个轮子打个广告好了,减少 redux 使用成本的非常简单的一个状态管理库 https://github.com/shadeofgod/reackt
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1320 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 17:13 · PVG 01:13 · LAX 10:13 · JFK 13:13
    ♥ Do have faith in what you're doing.