Skip to main content

Angular - Observables

Observables

Observables provide support for passing messages between publishers and subscribers in your application. Observables offer significant benefits over other techniques for event handling, asynchronous programming, and handling multiple values.
Observables are declarative—that is, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.
An observable can deliver multiple values of any type—literals, messages, or events, depending on the context. The API for receiving values is the same whether the values are delivered synchronously or asynchronously. Because setup and teardown logic are both handled by the observable, your application code only needs to worry about subscribing to consume values, and when done, unsubscribing. Whether the stream was keystrokes, an HTTP response, or an interval timer, the interface for listening to values and stopping listening is the same.
Because of these advantages, observables are used extensively within Angular, and are recommended for app development as well.

Basic usage and terms

As a publisher, you create an Observable instance that defines a subscriber function. This is the function that is executed when a consumer calls the subscribe() method. The subscriber function defines how to obtain or generate values or messages to be published.
To execute the observable you have created and begin receiving notifications, you call its subscribe()method, passing an observer. This is a JavaScript object that defines the handlers for the notifications you receive. The subscribe() call returns a Subscription object that has an unsubscribe() method, which you call to stop receiving notifications.
Here's an example that demonstrates the basic usage model by showing how an observable could be used to provide geolocation updates.
Observe geolocation updates
  1. // Create an Observable that will start listening to geolocation updates
  2. // when a consumer subscribes.
  3. const locations = new Observable((observer) => {
  4. // Get the next and error callbacks. These will be passed in when
  5. // the consumer subscribes.
  6. const {next, error} = observer;
  7. let watchId;
  8.  
  9. // Simple geolocation API check provides values to publish
  10. if ('geolocation' in navigator) {
  11. watchId = navigator.geolocation.watchPosition(next, error);
  12. } else {
  13. error('Geolocation not available');
  14. }
  15.  
  16. // When the consumer unsubscribes, clean up data ready for next subscription.
  17. return {unsubscribe() { navigator.geolocation.clearWatch(watchId); }};
  18. });
  19.  
  20. // Call subscribe() to start listening for updates.
  21. const locationsSubscription = locations.subscribe({
  22. next(position) { console.log('Current Position: ', position); },
  23. error(msg) { console.log('Error Getting Location: ', msg); }
  24. });
  25.  
  26. // Stop listening for location after 10 seconds
  27. setTimeout(() => { locationsSubscription.unsubscribe(); }, 10000);

Defining observers

A handler for receiving observable notifications implements the Observer interface. It is an object that defines callback methods to handle the three types of notifications that an observable can send:
NOTIFICATION TYPEDESCRIPTION
nextRequired. A handler for each delivered value. Called zero or more times after execution starts.
errorOptional. A handler for an error notification. An error halts execution of the observable instance.
completeOptional. A handler for the execution-complete notification. Delayed values can continue to be delivered to the next handler after execution is complete.
An observer object can define any combination of these handlers. If you don't supply a handler for a notification type, the observer ignores notifications of that type.

Subscribing

An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.
In order to show how subscribing works, we need to create a new observable. There is a constructor that you use to create new instances, but for illustration, we can use some static methods on the Observable class that create simple observables of frequently used types:
  • Observable.of(...items)—Returns an Observable instance that synchronously delivers the values provided as arguments.
  • Observable.from(iterable)—Converts its argument to an Observable instance. This method is commonly used to convert an array to an observable.
Here's an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console:
Subscribe using observer
  1. // Create simple observable that emits three values
  2. const myObservable = Observable.of(1, 2, 3);
  3.  
  4. // Create observer object
  5. const myObserver = {
  6. next: x => console.log('Observer got a next value: ' + x),
  7. error: err => console.error('Observer got an error: ' + err),
  8. complete: () => console.log('Observer got a complete notification'),
  9. };
  10.  
  11. // Execute with the observer object
  12. myObservable.subscribe(myObserver);
  13. // Logs:
  14. // Observer got a next value: 1
  15. // Observer got a next value: 2
  16. // Observer got a next value: 3
  17. // Observer got a complete notification

Alternatively, the subscribe() method can accept callback function definitions in line, for nexterror, and complete handlers. For example, the following subscribe() call is the same as the one that specifies the predefined observer:
Subscribe with positional arguments
myObservable.subscribe(
  x => console.log('Observer got a next value: ' + x),
  err => console.error('Observer got an error: ' + err),
  () => console.log('Observer got a complete notification')
);

In either case, a next handler is required. The error and complete handlers are optional.
Note that a next() function could receive, for instance, message strings, or event objects, numeric values, or structures, depending on context. As a general term, we refer to data published by an observable as a stream. Any type of value can be represented with an observable, and the values are published as a stream.

Creating observables

Use the Observable constructor to create an observable stream of any type. The constructor takes as its argument the subscriber function to run when the observable’s subscribe() method executes. A subscriber function receives an Observer object, and can publish values to the observer's next() method.
For example, to create an observable equivalent to the Observable.of(1, 2, 3) above, you could do something like this:
Create observable with constructor
  1. // This function runs when subscribe() is called
  2. function sequenceSubscriber(observer) {
  3. // synchronously deliver 1, 2, and 3, then complete
  4. observer.next(1);
  5. observer.next(2);
  6. observer.next(3);
  7. observer.complete();
  8.  
  9. // unsubscribe function doesn't need to do anything in this
  10. // because values are delivered synchronously
  11. return {unsubscribe() {}};
  12. }
  13.  
  14. // Create a new Observable that will deliver the above sequence
  15. const sequence = new Observable(sequenceSubscriber);
  16.  
  17. // execute the Observable and print the result of each notification
  18. sequence.subscribe({
  19. next(num) { console.log(num); },
  20. complete() { console.log('Finished sequence'); }
  21. });
  22.  
  23. // Logs:
  24. // 1
  25. // 2
  26. // 3
  27. // Finished sequence

To take this example a little further, we can create an observable that publishes events. In this example, the subscriber function is defined inline.
Create with custom fromEvent function
  1. function fromEvent(target, eventName) {
  2. return new Observable((observer) => {
  3. const handler = (e) => observer.next(e);
  4.  
  5. // Add the event handler to the target
  6. target.addEventListener(eventName, handler);
  7.  
  8. return () => {
  9. // Detach the event handler from the target
  10. target.removeEventListener(eventName, handler);
  11. };
  12. });
  13. }

Now you can use this function to create an observable that publishes keydown events:
Use custom fromEvent function
const ESC_KEY = 27;
const nameInput = document.getElementById('name') as HTMLInputElement;

const subscription = fromEvent(nameInput, 'keydown')
  .subscribe((e: KeyboardEvent) => {
    if (e.keyCode === ESC_KEY) {
      nameInput.value = '';
    }
  });

Multicasting

A typical observable creates a new, independent execution for each subscribed observer. When an observer subscribes, the observable wires up an event handler and delivers values to that observer. When a second observer subscribes, the observable then wires up a new event handler and delivers values to that second observer in a separate execution.
Sometimes, instead of starting an independent execution for each subscriber, you want each subscription to get the same values—even if values have already started emitting. This might be the case with something like an observable of clicks on the document object.
Multicasting is the practice of broadcasting to a list of multiple subscribers in a single execution. With a multicasting observable, you don't register multiple listeners on the document, but instead re-use the first listener and send values out to each subscriber.
When creating an observable you should determine how you want that observable to be used and whether or not you want to multicast its values.
Let’s look at an example that counts from 1 to 3, with a one-second delay after each number emitted.
Create a delayed sequence
  1. function sequenceSubscriber(observer) {
  2. const seq = [1, 2, 3];
  3. let timeoutId;
  4.  
  5. // Will run through an array of numbers, emitting one value
  6. // per second until it gets to the end of the array.
  7. function doSequence(arr, idx) {
  8. timeoutId = setTimeout(() => {
  9. observer.next(arr[idx]);
  10. if (idx === arr.length - 1) {
  11. observer.complete();
  12. } else {
  13. doSequence(arr, idx++);
  14. }
  15. }, 1000);
  16. }
  17.  
  18. doSequence(seq, 0);
  19.  
  20. // Unsubscribe should clear the timeout to stop execution
  21. return {unsubscribe() {
  22. clearTimeout(timeoutId);
  23. }};
  24. }
  25.  
  26. // Create a new Observable that will deliver the above sequence
  27. const sequence = new Observable(sequenceSubscriber);
  28.  
  29. sequence.subscribe({
  30. next(num) { console.log(num); },
  31. complete() { console.log('Finished sequence'); }
  32. });
  33.  
  34. // Logs:
  35. // (at 1 second): 1
  36. // (at 2 seconds): 2
  37. // (at 3 seconds): 3
  38. // (at 3 seconds): Finished sequence

Notice that if you subscribe twice, there will be two separate streams, each emitting values every second. It looks something like this:
Two subscriptions
  1. // Subscribe starts the clock, and will emit after 1 second
  2. sequence.subscribe({
  3. next(num) { console.log('1st subscribe: ' + num); },
  4. complete() { console.log('1st sequence finished.'); }
  5. });
  6.  
  7. // After 1/2 second, subscribe again.
  8. setTimeout(() => {
  9. sequence.subscribe({
  10. next(num) { console.log('2nd subscribe: ' + num); },
  11. complete() { console.log('2nd sequence finished.'); }
  12. });
  13. }, 500);
  14.  
  15. // Logs:
  16. // (at 1 second): 1st subscribe: 1
  17. // (at 1.5 seconds): 2nd subscribe: 1
  18. // (at 2 seconds): 1st subscribe: 2
  19. // (at 2.5 seconds): 2nd subscribe: 2
  20. // (at 3 seconds): 1st subscribe: 3
  21. // (at 3 seconds): 1st sequence finished
  22. // (at 3.5 seconds): 2nd subscribe: 3
  23. // (at 3.5 seconds): 2nd sequence finished

Changing the observable to be multicasting could look something like this:
Create a multicast subscriber
  1. function multicastSequenceSubscriber() {
  2. const seq = [1, 2, 3];
  3. // Keep track of each observer (one for every active subscription)
  4. const observers = [];
  5. // Still a single timeoutId because there will only ever be one
  6. // set of values being generated, multicasted to each subscriber
  7. let timeoutId;
  8.  
  9. // Return the subscriber function (runs when subscribe()
  10. // function is invoked)
  11. return (observer) => {
  12. observers.push(observer);
  13. // When this is the first subscription, start the sequence
  14. if (observers.length === 1) {
  15. timeoutId = doSequence({
  16. next(val) {
  17. // Iterate through observers and notify all subscriptions
  18. observers.forEach(obs => obs.next(val));
  19. },
  20. complete() {
  21. // Notify all complete callbacks
  22. observers.forEach(obs => obs.complete());
  23. }
  24. }, seq, 0);
  25. }
  26.  
  27. return {
  28. unsubscribe() {
  29. // Remove from the observers array so it's no longer notified
  30. observers.splice(observers.indexOf(observer), 1);
  31. // If there's no more listeners, do cleanup
  32. if (observers.length === 0) {
  33. clearTimeout(timeoutId);
  34. }
  35. }
  36. };
  37. };
  38. }
  39.  
  40. // Run through an array of numbers, emitting one value
  41. // per second until it gets to the end of the array.
  42. function doSequence(observer, arr, idx) {
  43. return setTimeout(() => {
  44. observer.next(arr[idx]);
  45. if (idx === arr.length - 1) {
  46. observer.complete();
  47. } else {
  48. doSequence(observer, arr, idx++);
  49. }
  50. }, 1000);
  51. }
  52.  
  53. // Create a new Observable that will deliver the above sequence
  54. const multicastSequence = new Observable(multicastSequenceSubscriber);
  55.  
  56. // Subscribe starts the clock, and begins to emit after 1 second
  57. multicastSequence.subscribe({
  58. next(num) { console.log('1st subscribe: ' + num); },
  59. complete() { console.log('1st sequence finished.'); }
  60. });
  61.  
  62. // After 1 1/2 seconds, subscribe again (should "miss" the first value).
  63. setTimeout(() => {
  64. multicastSequence.subscribe({
  65. next(num) { console.log('2nd subscribe: ' + num); },
  66. complete() { console.log('2nd sequence finished.'); }
  67. });
  68. }, 1500);
  69.  
  70. // Logs:
  71. // (at 1 second): 1st subscribe: 1
  72. // (at 2 seconds): 1st subscribe: 2
  73. // (at 2 seconds): 2nd subscribe: 2
  74. // (at 3 seconds): 1st subscribe: 3
  75. // (at 3 seconds): 1st sequence finished
  76. // (at 3 seconds): 2nd subscribe: 3
  77. // (at 3 seconds): 2nd sequence finished

Multicasting observables take a bit more setup, but they can be useful for certain applications. Later we will look at tools that simplify the process of multicasting, allowing you to take any observable and make it multicasting.

Error handling

Because observables produce values asynchronously, try/catch will not effectively catch errors. Instead, you handle errors by specifying an error callback on the observer. Producing an error also causes the observable to clean up subscriptions and stop producing values. An observable can either produce values (calling the next callback), or it can complete, calling either the complete or error callback.
myObservable.subscribe({
  next(num) { console.log('Next num: ' + num)},
  error(err) { console.log('Received an errror: ' + err)}
});

Error handling (and specifically recovering from an error) is covered in more detail in a later section.

Comments