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

2020-02-18 08:06:32 +08:00
 shadeofgod

开门直接放链接吧 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

1736 次点击
所在节点    程序员
1 条回复
shadeofgod
2020-02-18 08:21:27 +08:00
顺便再给另一个轮子打个广告好了,减少 redux 使用成本的非常简单的一个状态管理库 https://github.com/shadeofgod/reackt

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/645412

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX