How to calculate the **current flow value** based on current consumption values?

Hi All!
I’m trying to create water flow sensor (in l/min), based on the sensor that shows water consumption (for example, in litres). I used the combination of statistics sensor with max_age: minutes: 1 and template sensor, that shows change attribute of that statistics sensor.

But I discovered that statistics sensor stops update its values when water consumption stops. It just keeps last knows values. Such a behaviour together with defined max_age attribute looks for me incorrect. In case of max_age statistics should use moving values window instead of using last collected values.

So the question is how to calculate in Home Assistant the current flow value based on current consumption values?

Here is my config:

sensor: 
  - name: water_stat
    platform: statistics
    entity_id: sensor.raw_water # This is well working consumption sensor
    max_age:
      minutes: 1

  - platform: template
    sensors:
      raw_water_flow: 
        unit_of_measurement: l/min
        value_template: "{{ state_attr('sensor.water_stat', 'change') | float }}"

Indeed, after 1 minute you should not have any values left to calculate on (check the count attribute of the sensor, it should be zero), but what should the sensor then show?

Unknown?
Zero?
Or the last value?

Last value seems to be what the developer chose. You can submit an issue if you feel this is incorrect. It is in your case but there may be other cases/reasons for the choice.

Looks like there may be a derivative sensor in the works which you could use when it becomes available:

https://github.com/home-assistant/home-assistant/pull/26456

Might be related to this issue: https://github.com/home-assistant/home-assistant/issues/19800

If the monitored sensor does not change its state then the statistics sensor does not update anymore.

If you like you can try a patch that I have prepared which adds a listener to always update the statistics sensor after max_age, and I was hoping to get some feedback on before creating a PR:
https://github.com/exxamalte/home-assistant/commit/db1ef8f827f8281d713156d41bd91417e112433a

The derivative sensor seems to be just I need. Hope to see soon it in HA release. Thanks for advice!

I will test it. The solution proposed looks reasonable for me.