Avoid recreating persistent notification update function when subscribing (#108624)

I recently came up with an idea to look for callback functions
that get created over and over frequently by adding logging to
homeassistant.core.callback when its called to decorate
a function. This one happens a lot at runtime.
This commit is contained in:
J. Nick Koston 2024-01-21 17:45:45 -10:00 committed by GitHub
parent 573de95f21
commit 3d3f4ac293
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -4,6 +4,7 @@ from __future__ import annotations
from collections.abc import Callable, Mapping
from datetime import datetime
from enum import StrEnum
from functools import partial
import logging
from typing import Any, Final, TypedDict
@ -213,6 +214,21 @@ def websocket_get_notifications(
)
@callback
def _async_send_notification_update(
connection: websocket_api.ActiveConnection,
msg_id: int,
update_type: UpdateType,
notifications: dict[str, Notification],
) -> None:
"""Send persistent_notification update."""
connection.send_message(
websocket_api.event_message(
msg_id, {"type": update_type, "notifications": notifications}
)
)
@callback
@websocket_api.websocket_command(
{vol.Required("type"): "persistent_notification/subscribe"}
@ -225,19 +241,9 @@ def websocket_subscribe_notifications(
"""Return a list of persistent_notifications."""
notifications = _async_get_or_create_notifications(hass)
msg_id = msg["id"]
@callback
def _async_send_notification_update(
update_type: UpdateType, notifications: dict[str, Notification]
) -> None:
connection.send_message(
websocket_api.event_message(
msg["id"], {"type": update_type, "notifications": notifications}
)
)
notify_func = partial(_async_send_notification_update, connection, msg_id)
connection.subscriptions[msg_id] = async_dispatcher_connect(
hass, SIGNAL_PERSISTENT_NOTIFICATIONS_UPDATED, _async_send_notification_update
hass, SIGNAL_PERSISTENT_NOTIFICATIONS_UPDATED, notify_func
)
connection.send_result(msg_id)
_async_send_notification_update(UpdateType.CURRENT, notifications)
notify_func(UpdateType.CURRENT, notifications)