Skip to main content

Fundamentals of Rxjs Observable, Observer, Subscription

 What is Rxjs  ?

-> RxJS stands for Reactive Extensions for JavaScript.

->A new way to handle asynchronous operations, events and data streams.

-> Heavily in Angular because Angular's core feactures(like HttpClient, FromControl,valueChanges, and routing) all use Observables under the hood.

Why RxJS in Angular?

Handle Continuous Data

=>Unlike a promise (which resolves once), streams handle multiple values over time. Perfect for user interactions, WebSockets, or real-time data.

=> You can combine, filter, and transform streams easily with operators like map, filter, merge, and switchMap.

=> Instead of manually managing async events, you just declare what you want to happen.

For example: “Listen to input, wait 300ms, then call API” can be written in a clean chain of operators

Whether it’s HTTP requests, user inputs, or WebSocket connections — all can be modeled as streams. This gives a consistent way to handle asynchronous tasks.

=> Working with HTTP: All HttpClient methods return Observables

=> Form input tracking: valueChanges returns an Observable

=> Route parameters: ActivatedRoute.paramMap is an Observable

=> State management: RxJS is the foundation of libraries like NgRx

=> Building responsive UIs: You can react to user inputs, data changes, and server responses easily using RxJS.

What is an Observable?

=> Think of an Observable like a Netflix subscription or a Prime subscription You subscribe once and keep getting movies (data) over time.

=> Observables can emit multiple values over time

=>They can complete, error out, or keep streaming

=> We need to subscribe to start receiving values

=> Of, From, interval, timer, fromEvent

1. Observable – The Producer

An Observable is like a blueprint for a stream of data/events.

  • It defines what kind of values will be emitted (numbers, strings, events, API responses, etc.).
  • It doesn’t start producing values until someone subscribes.

 Think of it like a radio station:

  • The radio waves are already set up,
  • But unless you tune in (subscribe), you won’t hear anything

Creating and Subscribing to Observables

2. Observer – The Consumer

An Observer is simply the receiver of the values from the observable.
It’s an object with three optional methods:

  • receives emitted values
  • handles errors
  • runs when the observable finishes

3. Subscription – The Connection

A Subscription is what you get when you connect an Observer to an Observable.

  • It starts the execution of the observable.
  • You can also unsubscribe to stop receiving values (important for performance and memory management).



git Repo

Comments

© 2020 The JavaDS Hub

Designed by Open Themes & Nahuatl.mx.