Subscription to events with asyncio - async_on_remove

Hello, I’m vibe coding myself through a custom integration. yet I strive to understand the code generated. Here is the piece I stumbled over:

async def async_added_to_hass(self) -> None:
        """Run when entity is added to hass."""
        await super().async_added_to_hass()

        # Subscribe to temperature sensor state changes
        self.async_on_remove(
            async_track_state_change_event(self.hass, [self._temperature_sensor], self._async_temperature_changed, ))


        # Get initial temperature
        await self._async_update_temperature()
        await self._async_control_heating()

I first figured the self.async_on_removeis wrong, as I want the integration to subscribe to temperature changes while it’s active, not just when it’s removed (this is how I interpret the call).

However, it does work as intended (temp changes trigger recalculation) and there is a piece of documentation here: Thread safety with asyncio | Home Assistant Developer Docs that seems to imply the same structure for subscribing to events.

Can anyone explain this to me and confirm that async_on_remove is indeed the correct way to subscribe to changes?

thx

I think this page will help understand what that method is doing. It’s basically a shorthand method that cleans up the subscriptions when the integration is tearing down, similar to using async_will_remove_from_hass but without manually needing to store the subscription.

1 Like

a gosh. Think I get it now. Of course, the argument async_track_state_change_event(self.hass, [self._temperature_sensor], self._async_temperature_changed, )) will be executed immediately, the returning some sort of handler which then can be used by the outer async_on_remove to clean up the subscription… Correct?