Observer Pattern

Draft Disclaimer: Please note that this article is currently in draft form and may undergo revisions before final publication. The content, including information, opinions, and recommendations, is subject to change and may not represent the final version. We appreciate your understanding and patience as we work to refine and improve the quality of this article. Your feedback is valuable in shaping the final release.

Language Mismatch Disclaimer: Please be aware that the language of this article may not match the language settings of your browser or device.
Do you want to read articles in English instead ?

Observer Pattern

Summary

  • What is a design pattern ?
  • What is Observer pattern ?
  • How useful is the Observer pattern ?

abstract class Observer<T> {
  val listeners: ArrayList<ObserverListener> = ArrayList()
  abstract fun setValue (value: T)
  fun notify (value: T) {
    listeners.forEach { listener -> listener.onChanged(value) }
  }
  
  fun observe (listener: ObserverListener) {
    this.listeners.add(listener)
  }

  interface ObserverListener<T> {
    fun onChanged(value: T)
  } 
}
class CounterObserver: Observer<Int> {
  var counter: Int
  override setValue (value: Int) {
      counter = value
      notify(value)
  }

  fun increment () {
    this.setValue(count + 1)
  }

  fun decrement () {
    this.setValue(count - 1)
  }
}

// usage
val counterObserver = CounterObserver()
counterObserver.observe(object: ObserverListener<Int> {
    override fun onChanged (value: Int) {
        // update UI
    }
})

Livedata as Observer that is lifecycle aware.