I want to retain previous value if current value is not valid in MQTT sensor

So, I have a custom smart meter adapter, which reports the values via MQTT. My sensor is defined like this:

- platform: mqtt
  state_topic: '/smartmeter/sensor/low_tariff_energy'
  unit_of_measurement: 'Wh'
  icon: 'mdi:flash'
  name: 'Energy LT'
  device_class: energy
  state_class: total_increasing
  value_template: '{{ value | int(default=0) }}'

As the decryption code occasionaly has some hiccups, the MQTT sensor sometimes gets strange values - for example, the values come in a sequence like: 230000, 230021, 230048, 4545454545454, 230067
This of course screws the whole statistics. So, I would like to define the value_template in a way, that it disregards the new value (and the previous value reimains), if the new value is f.e. more than 1000 higher or lower than current value. What would I have to add to the value_template to achieve this?

I tried to experiment with example from THIS thread, but I couldn’t make it work - maybe because at the initialization the value is empty (no retain available) and compared to the new value the result is always false?.

Thx in advance for all your inputs.

Well, solved it myself and posting the solution here, if anyone might have the same problem.
For my scenario the following code works (eliminating unknown values at HA/MQTT/… restart):

- platform: mqtt
  state_topic: '/smartmeter/sensor/low_tariff_energy'
  unit_of_measurement: 'Wh'
  icon: 'mdi:flash'
  name: 'Energy LT'
  device_class: energy
  state_class: total_increasing
  value_template: >- 
    {% if  states('sensor.energy_lt') == 'unknown'  %}
    {{ value }}
    {% elif ( value | int (default=0) - states('sensor.energy_lt') | int (default=0)) | abs > 1000 %}
    {{ states('sensor.energy_lt') | int (default=0) }}
    {% else %}
    {{ value }}
    {% endif %}