Observer Pattern in Android
Observer Pattern in Android
The Observer pattern establishes a one to many dependency between objects so that when one object (the subject) changes state, all its dependents (observers) are notified and updated automatically. In Android, this pattern is the foundation of reactive UI architectures where the data layer emits state changes and the UI layer observes and renders them. By the end of this lesson, you will be able to:
- Explain the subject/observer relationship and how state change notifications propagate.
- Compare
StateFlow,SharedFlow,LiveData, and manual observer implementations in Android. - Describe how lifecycle awareness prevents resource leaks in Android observer implementations.
- Apply the pattern to connect ViewModels to UI layers using Flow and Compose state.
- Identify the tradeoffs between hot and cold observable streams in Android.
Subject and Observer Mechanics
The pattern has two participants. The subject maintains a list of registered observers and notifies them when its internal state changes. Each observer implements a callback interface that the subject invokes during notification. The subject does not know the concrete type of its observers. It only knows the observer interface.
interface Observer<T> {
fun onChanged(value: T)
}
class Subject<T>(initialValue: T) {
private val observers = mutableListOf<Observer<T>>()
private var value: T = initialValue
fun addObserver(observer: Observer<T>) { observers.add(observer) }
fun removeObserver(observer: Observer<T>) { observers.remove(observer) }
fun setValue(newValue: T) {
value = newValue
observers.forEach { it.onChanged(newValue) }
}
}
This decoupling means the subject can exist in a data layer module with no dependency on the UI layer. The UI layer registers as an observer and reacts to changes. Adding new observers requires no modification to the subject, satisfying the open/closed principle.
The manual implementation above illustrates the core concept, but it lacks thread safety and lifecycle awareness. In production Android code, you would use StateFlow, LiveData, or SharedFlow instead of rolling your own, since these implementations handle concurrency, backpressure, and lifecycle integration out of the box.
StateFlow as the Modern Observer
In Kotlin coroutines, StateFlow is a hot observable stream that always holds a current value and emits updates to all collectors. It is the standard way to implement the Observer pattern in modern Android development.
This interview continues for subscribers
Subscribe to Dove Letter for full access to exclusive interviews about Android and Kotlin development.
Become a Sponsor