A sort of a reminder I put together for myself, this time it’s some of the ES6 additions to javascript.

Links

https://www.tektutorialshub.com/angular/angular-observable-tutorial-using-rxjs

https://www.tektutorialshub.com/angular/subjects-in-angular/

Observables

Observable is a function that converts the ordinary stream of data into an observable stream of data. You can think of Observable as a wrapper around the ordinary stream of data.

Observable stream or simple Observable emits the value from the stream asynchronously. It emits the complete signals when the stream completes or an error signal if the stream errors out.

Observables are declarative. You define an observable function just like any other variable. The observable starts to emit values only when someone subscribes to it.

Observers

The Observable on its own is useless unless someone consumes the value emitted by the observable. We call them observers or subscribers.

The observers communicate with the Observable using callbacks

The observer must subscribe with the observable to receive the value from the observer. While subscribing it optionally passes the three callbacks. next(), error() & complete()

The observable invokes the next() callback whenever the value arrives in the stream. It passes the value as the argument to the next callback. If the error occurs, then the error() callback is invoked. It invokes the complete() callback when the stream completes.

Creating an Observable

obs = new Observable((observer) => {
     console.log(“Observable starts”)
     observer.next("1")
     observer.next("2")
     observer.next("3")
     observer.next("4")
     observer.next("5")
   })

Subscribing to Observable

ngOnInit() {
 
    this.obs.subscribe(
      val => { console.log(val) }, //next callback
      error => { console.log("error") }, //error callback
      () => { console.log("Completed") } //complete callback
    )
}

Leave a Reply

Your email address will not be published. Required fields are marked *