Skip to content

Commit

Permalink
feat: unsubscribe from channel
Browse files Browse the repository at this point in the history
  • Loading branch information
KatoakDR committed Dec 31, 2023
1 parent 606c1b9 commit 4240ba8
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
5 changes: 4 additions & 1 deletion electron/main/ipc/ipc.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
* The main process must provide call-response handlers for this API.
* Excludes the `onMessage` push-style API from main to renderer.
*/
export type IpcInvokableEvent = keyof Omit<AppAPI, 'onMessage'>;
export type IpcInvokableEvent = keyof Omit<
AppAPI,
'onMessage' | 'removeAllListeners'
>;

export interface IpcInvokeHandler<K extends IpcInvokableEvent> {
(params: Parameters<AppAPI[K]>): ReturnType<AppAPI[K]>;
Expand Down
10 changes: 10 additions & 0 deletions electron/preload/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,16 @@ declare const appAPI: {
channel: string,
callback: (event: Electron.IpcRendererEvent, ...args: any[]) => void
) => void;
/**
* Allows the renderer to unsubscribe from messages from the main process.
* Removes all listeners added by the `onMessage` API for a channel.
*
* For example, when subscribing to messages in a react app, the
* `useEffect` hook will subscribe multiple times, once per time the hook
* is regenerated. To prevent this, ensure to unsubscribe in the hook's
* destroy function. https://stackoverflow.com/a/73458622/470818
*/
removeAllListeners(channel: string): void;
};
declare global {
type TypeOfAppAPI = typeof appAPI;
Expand Down
12 changes: 12 additions & 0 deletions electron/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,18 @@ const appAPI = {
) => {
ipcRenderer.on(channel, callback);
},
/**
* Allows the renderer to unsubscribe from messages from the main process.
* Removes all listeners added by the `onMessage` API for a channel.
*
* For example, when subscribing to messages in a react app, the
* `useEffect` hook will subscribe multiple times, once per time the hook
* is regenerated. To prevent this, ensure to unsubscribe in the hook's
* destroy function. https://stackoverflow.com/a/73458622/470818
*/
removeAllListeners(channel: string) {
ipcRenderer.removeAllListeners(channel);
},
};

declare global {
Expand Down

0 comments on commit 4240ba8

Please sign in to comment.