We’ll also learn about the related concepts such as:
BehaviorSubject
and ReplaySubject
.Observable
with AsyncPipe
An Observable is an entity that emits (or publishes) multiple data values (stream of data) over time and asynchronously.
This is the definition of an Observable from the RxJS docs
Observable represents the idea of an invokable collection of future values or events.## Observers and Subscriptions
There are also related concepts that you’ll work with when using Observables which are Observers and Subscriptions.
Observers are also called listeners (or consumers) as they can listen or subscribe to get the observed data.
From the RxJS docs:
Observable represents the idea of an invokable collection of future values or events.
Subscriptions are objects that are returned when you subscribe to an Observable. They contain many methods such as theunsubscribe()
method that you can call to unsubscribe from receving published values from the Observable.
From the official docs:
Observable represents the idea of an invokable collection of future values or events.## What is a Subject in RxJS
A Subject is a special type of Observable that observers can also subscribe to it to receive published values but with one difference: The values are multicasted to many Observers.
Observable represents the idea of an invokable collection of future values or events.
Unicast simply means that each subscribed observer has an independent execution of the Observable while multicast means that the Observable execution is shared by multiple Observers.
Observable represents the idea of an invokable collection of future values or events.
So when using Subjects instead of plain Observables, all subscribed Observers will get the same values of emitted data.
Observable represents the idea of an invokable collection of future values or events.## Hot and Cold Observables
Unlike regular Observables, Subjects are called hot. A hot Observable starts emitting events even before any observer subscribes to it which means observers may lose previous emitted values if they don’t subscribe at that right time while cold Observables ****start emitting values when at least one observer is subscribed.
Observable represents the idea of an invokable collection of future values or events.## RxJS’
**BehaviorSubject**
and**ReplaySubject**
RxJS provides two other types of Subjects: BehaviorSubject
and ReplaySubject
.
With a normal Subject, Observers that are subscribed at a point later will not receive data values emitted before their subscriptions. In many situations, this is not the desired behavior we want to implement. This can be solved using BehaviorSubject
and ReplaySubject
.
ReplaySubject
works by using a buffer that keeps the emitted values and re-emit them when new Observers are subscribed.
BehaviorSubject
works like ReplaySubject
but only re-emits the last emitted value.
You can create an RxJS Observable using the Observable.create()
method which takes a function with an observer
argument. You can then subscribe to the returned Observable instance.
There many other methods to create Observables besides the static create()
method:
BehaviorSubject
and ReplaySubject
.Observable
with AsyncPipe
We’ll see these creation methods by example later.
After creating an Observable
, you can subscribe to it using the subscribe()
method on the instance which returns an instance of Subscription
.
Let’s now see a simple example of creating and working with an Observable.
First let’s create an Observable:
let ob$ = Observable.create((observer) => {
observer.next("A new value!");
});
We create an ob$
Observable and we define the logic that our Observable is supposed to do in the body of the passed in method.
In this example, the Observable will simply emit the A new value! value to the subscribed Observer.
Observable represents the idea of an invokable collection of future values or events.
We call thenext()
method of the observer object to inform it of the available values.
Observable represents the idea of an invokable collection of future values or events.> Observable represents the idea of an invokable collection of future values or events.
Next, let’s create an observer object:
let observer = {
next: data => console.log( 'Data received: ', data),
complete: data => console.log('Completed'),
};
An observer is a plain JavaScript object that contains methods such as next()
, complete()
and error()
. This means it knows how to get notified by the Observable.
Observable represents the idea of an invokable collection of future values or events.
Finally, let’s subscribe to ourob$
Observable and return aSubscription
:
let subscription = ob$.subscribe(observer);
Once you susbscribe to the ob$
Observable, you’ll get the following output in the console:
Data received: A new value!
Angular uses the RxJS Observable as a built-in type for many of its APIs such as:
BehaviorSubject
and ReplaySubject
.Observable
with AsyncPipe
Let’s assume, you have an Angular component and the Router service injected as router
. This example from StackOverflow shows you how you can subscribe to the router events for detecting a route change:
import { Component } from '@angular/core';
import { Router, Event, NavigationStart, NavigationEnd, NavigationError } from '@angular/router';
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`
})
export class AppComponent {
constructor(private router: Router) {
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
console.log("Navigation start");
}
if (event instanceof NavigationEnd) {
console.log("Navigation end");
}
if (event instanceof NavigationError) {
console.log(event.error);
}
});
}
}
BehaviorSubject
and ReplaySubject
.Observable
with AsyncPipe
How to Use RxJS 6 Observable in Your Angular Code
Angular uses Observables (implemented with the RxJS library) for all asynchronous events. If you are using Angular CLI 6|7, RxJS 6 will be installed by default on your project.
Otherwise you can install it via npm using:
$ npm install rxjs --save
To be able to use the Observable symbol in your code, you first need to import it:
import { Observable } from 'rxjs';
This is the new import path in RxJS 6 which is different from RxJS 5.
The new Angular HttpClient
works with Observables by default. Methods such as get()
, post()
, put()
and delete()
return an instance of the Observable interface.
HTTP requests are only sent when we subscribe to the Observable.
This is an example of making an HTTP request:
getItems(): Observable<Item[]> {
return this.httpClient.get<Item[]>(this.itemUrl);
}
We assume that you have injected the HttpClient
service as httpClient.
**Observable**
with **AsyncPipe**
Angular AsyncPipe
subscribes to Observable and returns the emitted data. For example. Let’s suppose we have this method:
getItems(): Observable {
this.items$ = this.httpClient.get(this.itemUrl);
}
The items$
variable is of type Observable`.
After calling the getItems()
method on the component we can use the async
pipe in the component template to subscribe to the returned Observable:
Observables are used for better support of event handling, asynchronous programming, and handling multiple values. When you define an Observable to publish some values for a consumer, the values are not emitted until you actually subscribe to the Observable.
The Consumer that subscribes to the Observable keeps receiving values until the Observable is completed or the consumer unsubscribes from the observable.
Let’s start by defining an observable that provides a stream of updates
In this tutorial, you have learned what an Observable is — An object that emits or publishes values over time and asynchronously.
You have learned about the related concepts to Observables such as Observers and Subscriptions — Observers are objects that listen and consume values published by an Observable and Subscriptions are the objects returned from the subscribe()
method (They are usually used to unsubscribe the Observer from the Observable).
You have also learned about special types of Observables such as Subjects, behavior Subjects (BehaviorSubject
) and replay Subjects (ReplaySubject
) and also the difference between unicast and multicast Observables. As a reminder a multicast Observable shares its execution between all its Observers.
You learned about cold and hot Observables — hot refers to when the Obseravble starts publishing values when it’s created even before getting any subscriptions.
*Originally published at *techiediaries.com*** ***on 09 Sep 2019
====================================================
Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter
Angular 8 RxJS Multiple HTTP Request using the forkJoin Example
Better RxJS code with pointfree style
RxJS tutorial - Multiple HTTP requests in Angular 8 with forkJoin
Intro to RxJS Concepts with Vanilla JavaScript
Angular 6|7 RxJS 6 In-Depth Tutorial & Example
#angular #javascript #web-development