94.createObservable

Write a function named createObservable that returns an object implementing the Observer pattern.

The object - let's call it observable - should have the following properties:

  • subscribe - a method used by observers to subscribe to the observable. It should accept 1 parameter:

    • callback - a function that will be called when we want to notify the observers
  • unsubscribe - a method used by observers to unsubscribe from the observable. It should receive the same callback sent to the subscribe function as parameter

  • notify - a method used to notify the observers. It should accept 1 parameter:

    • data - any data that should be passed as parameter to the observers' callback functions

Example 1

class User {
  name;
  weatherObservable;

  constructor(name, weatherObservable) {
    this.name = name;
    this.weatherObservable = weatherObservable;
    this.weatherObservable.subscribe(this.onWeatherChange);
  }

  onWeatherChange = (weatherData) => {
    console.log(`${this.name} received weather updates: `, weatherData);
  }

  stopListening() {
    this.weatherObservable.unsubscribe(this.onWeatherChange);
  }
}

const weatherObservable = createObservable();
const bob = new User("Bob", weatherObservable);

/**
 * Should print:
 * Bob received weather updates: { temperature: 20, humidity: 80 }
 */
weatherObservable.notify({ temperature: 20, humidity: 80 });

/**
 * Should print:
 * Bob received weather updates:  { temperature: 25, humidity: 75 }
 */
weatherObservable.notify({ temperature: 25, humidity: 75 });

bob.stopListening();

// Should not print anything, because the user is no longer
// subscribed to the weatherObservable observable.
weatherObservable.notify({ temperature: 22, humidity: 68 });