How to get the old / previous value when you observe a Kivy Property

Viewed 42

If I have a kivy-widget with an observed property like this:

class SampleClass(BoxLayout):
    state = StringProperty("idle")
    
    (...)
    
    def on_state(self, instance, value):
        print("State changed to " + value)

The on_state method will be called, every time the state-property changes. The value argument will contain the new string or the value, the state-property is changed to.

But now I want to execute a function only, if the value of the state-property changes from one value to another. E.g. I want to execute a function, when the state-property changes from "idle" to "running" but not when it changes from "stopped" to "running".

The problem is that I can't find any way, to access the old or the previous value. I could write my own setter function and track the old values myself, but maybe there is another, more elegant way of doing this.

enter code here
1 Answers
class SampleClass(BoxLayout):
    _state = StringProperty("idle")

    (...)

    def get_state(self):
        return self._state

    def set_state(self, new_state):
        old_state = self._state
        self.on_state_change(old_state, new_state)
        self._state = new_state
        return True

    state = AliasProperty(get_state, set_state, cache=False, bind=['_state'])

Thanks to ApuCoder. With your comment I managed to do it a bit like this ...

Related