s3-kennisbank

View the Project on GitHub HU-SD-S3/s3-kennisbank

Observables

In earlier chapters, we explored various methods for exchanging data between web components. Most of these methods were event-driven, meaning the communication was triggered by user actions, such as clicking a button or changing an input field. For these view-layer-only interactions, using events is a suitable and effective solution.

However, there are scenarios where events from the view layer are not ideal:

In both cases, using DOM events is not appropriate, because the service layer should not interact with the DOM, and events are tightly coupled to the view layer and not suitable for broader data communication.

Observables

To solve this, we use Observables, which are based on the Observer Pattern. Think of Observables like push notifications for data. Any component that subscribes to an observable will be notified automatically when the data changes. This pattern is widely used in libraries like RxJS.

Here’s a clearer and more structured version of your explanation of the Observer Pattern:

classDiagram

  class Subject {
    +observerCollection
    +subscribe(observer: Observer)
    +unsubscribe(observer: Observer)
    +notify()
  }

  class Observer {
    <<abstract>>
    +update(data)
  }

  Subject o-- Observer

  class ConcreteObserverA
  class ConcreteObserverB

  Observer <|.. ConcreteObserverA
  Observer <|.. ConcreteObserverB

Observer Pattern explained

The Observer Pattern is a design pattern that enables an object (called the Subject) to maintain a list of dependents (called Observers) and automatically notify them of any state changes.

1. Subject

The Subject is the part of your app that has the data. It keeps a list of observers (other parts of your app that want to know when the data changes). It has three main actions:

2. Observer (Abstract)

This is like a rule or guideline. It says: “Every observer must have an update(data) method.” This method is what gets called when the Subject sends out a notification. It doesn’t do anything itself, it just acts as a ‘template’ that defines what observers should be able to do.

3. Concrete Observers (A & B)

These are the real observers, actual parts of your app that want updates. They follow the rule by implementing the update(data) method. They subscribe to the Subject so they can be notified when the data changes. When they get notified, they use the update(data) method to do something, like update the screen or log the change.


In the upcoming two sections, we’ll explore how to implement the Observer Pattern in practice. First, we’ll build an observable from scratch using vanilla JavaScript to understand the core mechanics. After that, we’ll use a library called RxJS, which simplifies working with observables and offers powerful tools for reactive programming.


Sources


:house: Home :arrow_backward: Signals
:arrow_up: Data Exchange Vanilla JS Observables :arrow_forward: