The Observable Value

Step 3: The Observable Value

Wrap a Subject around a piece of state and you get an observable value, the atom of every reactive system (a signal, a store, a ref). Reading is plain; writing notifies subscribers with the new value. The crucial detail: only fire when the value actually changes, so nothing recomputes needlessly.

  • set(value): if value differs from the current one, store it and notify subscribers with the new value; if it is equal, do nothing
Hints
Starter code
class Subject:
    def __init__(self):
        self._observers = []

    def subscribe(self, observer):
        self._observers.append(observer)
        def unsubscribe():
            if observer in self._observers:
                self._observers.remove(observer)
        return unsubscribe

    def notify(self, *args):
        for observer in self._observers:
            observer(*args)


class Observable:
    def __init__(self, value=None):
        self._value = value
        self._subject = Subject()

    def get(self):
        return self._value

    def subscribe(self, observer):
        return self._subject.subscribe(observer)

    def set(self, value):
        """Update the value and notify subscribers, but only on a real change."""
        # TODO: compare the incoming value against the one already held in
        #   self._value; when they are equal, leave everything untouched. Otherwise
        #   record it as the new current value first, then have self._subject notify
        #   observers, passing them that new value.
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.