What are observables - amresh087/newronaRepos GitHub Wiki

  1. What are observables?

    Observables are declarative which provide support for passing messages between publishers and subscribers in your application. They are mainly used for event handling, asynchronous programming, and handling multiple values. In this case, 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.

  2. What is RxJS?

    RxJS is a library for composing asynchronous and callback-based code in a functional, reactive style using Observables. Many APIs such as HttpClient produce and consume RxJS Observables and also uses operators for processing observables.

    For example, you can import observables and operators for using HttpClient as below,

    import { Observable, throwError } from 'rxjs';
    import { catchError, retry } from 'rxjs/operators';
    
  3. What is subscribing?

    An Observable instance begins publishing values only when someone subscribes to it. So you need to subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.

    Let's take an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console.

    // Creates an observable sequence of 5 integers, starting from 1
    const source = range(1, 5);
    
    // Create observer object
    const myObserver = {
      next: x => console.log('Observer got a next value: ' + x),
      error: err => console.error('Observer got an error: ' + err),
      complete: () => console.log('Observer got a complete notification'),
    };
    
    // Execute with the observer object and Prints out each item
    source.subscribe(myObserver);
    // => Observer got a next value: 1
    // => Observer got a next value: 2
    // => Observer got a next value: 3
    // => Observer got a next value: 4
    // => Observer got a next value: 5
    // => Observer got a complete notification
    
  4. What is an observable?

    An Observable is a unique Object similar to a Promise that can help manage async code. Observables are not part of the JavaScript language so we need to rely on a popular Observable library called RxJS. The observables are created using new keyword.

    Let see the simple example of observable,

    import { Observable } from 'rxjs';
    
    const observable = new Observable(observer => {
      setTimeout(() => {
        observer.next('Hello from a Observable!');
      }, 2000);
    });
    
  5. What is an observer?

    Observer is an interface for a consumer of push-based notifications delivered by an Observable. It has below structure,

    interface Observer<T> {
      closed?: boolean;
      next: (value: T) => void;
      error: (err: any) => void;
      complete: () => void;
    }
    

    A handler that implements the Observer interface for receiving observable notifications will be passed as a parameter for observable as below,

    myObservable.subscribe(myObserver);
    

    Note: If you don't supply a handler for a notification type, the observer ignores notifications of that type.

  6. What is the difference between promise and observable?

    Below are the list of differences between promise and observable:

    Observable Promise
    Declarative: Computation does not start until subscription, so they can run whenever you need the result Executes immediately on creation
    Provides multiple values over time Provides only one
    Subscribe method is used for error handling that facilitates centralized and predictable error handling Push errors to the child promises
    Provides chaining and subscription to handle complex applications Uses only .then() clause
  7. What is multicasting?

    Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution.

    Let's demonstrate the multi-casting feature:

    var source = Rx.Observable.from([1, 2, 3]);
    var subject = new Rx.Subject();
    var multicasted = source.multicast(subject);
    
    // These are, under the hood, `subject.subscribe({...})`:
    multicasted.subscribe({
      next: (v) => console.log('observerA: ' + v)
    });
    multicasted.subscribe({
      next: (v) => console.log('observerB: ' + v)
    });
    
    // This is, under the hood, `s
    
  8. How do you perform error handling in observables?

    You can handle errors by specifying an error callback on the observer instead of relying on try/catch, which are ineffective in asynchronous environment.

    For example, you can define error callback as below,

    myObservable.subscribe({
      next(num) { console.log('Next num: ' + num)},
      error(err) { console.log('Received an errror: ' + err)}
    });