V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
shadeofgod
V2EX  ›  程序员

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

  •  
  •   shadeofgod ·
    zoubingwu · 2020-02-18 08:06:32 +08:00 · 1723 次点击
    这是一个创建于 1542 天前的主题,其中的信息可能已经有所发展或是发生改变。

    开门直接放链接吧 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
       2020-02-18 08:21:27 +08:00
    顺便再给另一个轮子打个广告好了,减少 redux 使用成本的非常简单的一个状态管理库 https://github.com/shadeofgod/reackt
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5056 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 09:51 · PVG 17:51 · LAX 02:51 · JFK 05:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.