diff --git a/src/panels/logbook/ha-logbook.ts b/src/panels/logbook/ha-logbook.ts index 342a9890a0..fe5ecfb54c 100644 --- a/src/panels/logbook/ha-logbook.ts +++ b/src/panels/logbook/ha-logbook.ts @@ -138,7 +138,7 @@ export class HaLogbook extends LitElement { this._throttleGetLogbookEntries.cancel(); this._updateTraceContexts.cancel(); this._updateUsers.cancel(); - this._unsubscribeSetLoading(); + await this._unsubscribeSetLoading(); this._liveUpdatesEnabled = true; @@ -207,16 +207,26 @@ export class HaLogbook extends LitElement { ); } - private _unsubscribe() { + private async _unsubscribe(): Promise { if (this._subscribed) { - this._subscribed.then((unsub) => unsub?.()); - this._subscribed = undefined; + try { + const unsub = await this._subscribed; + if (unsub) { + await unsub(); + this._subscribed = undefined; + this._pendingStreamMessages = []; + } + } catch (err: any) { + // eslint-disable-next-line + console.error("Error unsubscribing:", err); + } } } public connectedCallback() { super.connectedCallback(); if (this.hasUpdated) { + // Ensure clean state before subscribing this._subscribeLogbookPeriod(this._calculateLogbookPeriod()); } } @@ -231,8 +241,8 @@ export class HaLogbook extends LitElement { * Setting this._logbookEntries to undefined * will put the page in a loading state. */ - private _unsubscribeSetLoading() { - this._unsubscribe(); + private async _unsubscribeSetLoading() { + await this._unsubscribe(); this._logbookEntries = undefined; this._pendingStreamMessages = []; } @@ -241,8 +251,8 @@ export class HaLogbook extends LitElement { * Setting this._logbookEntries to an empty * list will show a no results message. */ - private _unsubscribeNoResults() { - this._unsubscribe(); + private async _unsubscribeNoResults() { + await this._unsubscribe(); this._logbookEntries = []; this._pendingStreamMessages = []; } @@ -273,10 +283,12 @@ export class HaLogbook extends LitElement { throw new Error("Unexpected time specified"); } - private _subscribeLogbookPeriod(logbookPeriod: LogbookTimePeriod) { + private async _subscribeLogbookPeriod(logbookPeriod: LogbookTimePeriod) { if (this._subscribed) { return true; } + // Ensure any previous subscription is cleaned up + await this._unsubscribe(); this._subscribed = subscribeLogbook( this.hass, (streamMessage) => { @@ -304,7 +316,7 @@ export class HaLogbook extends LitElement { this._error = undefined; if (this._filterAlwaysEmptyResults) { - this._unsubscribeNoResults(); + await this._unsubscribeNoResults(); return; } @@ -312,7 +324,7 @@ export class HaLogbook extends LitElement { if (logbookPeriod.startTime > logbookPeriod.now) { // Time Travel not yet invented - this._unsubscribeNoResults(); + await this._unsubscribeNoResults(); return; }