diff --git a/src/client.ts b/src/client.ts index 7df626b..bc98b1e 100644 --- a/src/client.ts +++ b/src/client.ts @@ -7,6 +7,7 @@ import { Workspace, GwmCommand, Container, + EventSubscription, } from './types'; import { resolveWebSocketApi } from './websocket'; @@ -106,7 +107,7 @@ export class GwmClient { * * @param command WM command to run (eg. "focus workspace 1"). * @param contextContainer (optional) Container or ID of container to use as - * context. + * context. If not provided, this defaults to the currently focused container. * @throws If command fails. */ async runCommand( @@ -185,7 +186,9 @@ export class GwmClient { events: T, callback: SubscribeCallback, ): Promise { - await this.sendAndWaitReply(`subscribe -e ${events.join(',')}`); + const response = await this.sendAndWaitReply( + `subscribe -e ${events.join(',')}`, + ); const unlisten = this.onMessage((e) => { const serverMessage: ServerMessage = JSON.parse(e.data); @@ -199,10 +202,12 @@ export class GwmClient { } }); - // TODO: Properly unsubscribe from the event(s). Use `async` here to prevent - // breaking API changes in the future. return async () => { unlisten(); + + await this.sendAndWaitReply( + `unsubscribe ${response.subscriptionId}`, + ); }; } diff --git a/src/types/client-messages.ts b/src/types/client-messages.ts index 1fef311..51b59f1 100644 --- a/src/types/client-messages.ts +++ b/src/types/client-messages.ts @@ -5,6 +5,8 @@ export type SubscribeMessage = | `subscribe --events ${string}` | `subscribe -e ${string}`; +export type UnsubscribeMessage = `unsubscribe ${string}`; + export type InvokeCommandMessage = | `command "${GwmCommand}"` | `command "${GwmCommand}" --context-container-id ${string}` @@ -16,6 +18,7 @@ export type GetWindowsMessage = 'windows'; export type ClientMessage = | SubscribeMessage + | UnsubscribeMessage | InvokeCommandMessage | GetMonitorsMessage | GetWorkspacesMessage diff --git a/src/types/shared/event-subscription.ts b/src/types/shared/event-subscription.ts new file mode 100644 index 0000000..fb6df45 --- /dev/null +++ b/src/types/shared/event-subscription.ts @@ -0,0 +1,3 @@ +export interface EventSubscription { + subscriptionId: string; +} diff --git a/src/types/shared/index.ts b/src/types/shared/index.ts index 2883b24..b37ba65 100644 --- a/src/types/shared/index.ts +++ b/src/types/shared/index.ts @@ -1,6 +1,7 @@ export * from './border-delta'; export * from './container'; export * from './direction'; +export * from './event-subscription'; export * from './floating-placement'; export * from './floating-window'; export * from './maximized-window';