Young Devs Bin
๐Ÿ“ Today I Learned

Observer Pattern: Broadcasting Without Knowing Who's Listening

ยท1 min readยท#today-i-learned#design-pattern#kotlin#android

Second pattern this week: Observer. The setup was a lane control system โ€” a sensor detects a status change, and several components (speed controller, warning system, logger) all need to react without being wired directly to the sensor.

  • The subject shouldn't care who reacts or how โ€” it just keeps a list and notifies everyone, and each observer decides what to do with the update
  • Adding a new component that reacts to changes is one step: implement the observer interface and subscribe โ€” the subject itself never changes
  • Checking for a no-op update before notifying matters, otherwise observers fire on updates that didn't actually change anything
  • Runtime subscribe and unsubscribe means observers can come and go, which is useful when a component is only conditionally active
  • Once data starts arriving asynchronously, plain Observer isn't enough anymore โ€” that's when it's time to move to a StateFlow so a ViewModel can collect updates safely
  • Observer and StateFlow solve the same core problem at different layers: Observer for class-to-class notification, StateFlow for ViewModel-to-UI
  • Testing is simple โ€” mock the observer, trigger the update, and verify it got called with the right value