# What is RxJS - Simple & Code Examples

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using [Observables](https://blog.multignite.com/what-is-an-observable-in-reactive-programming-rxjs), which makes it easier to work with [asynchronous](https://blog.multignite.com/asynchronous-javascript-and-typescript) [data streams](https://blog.multignite.com/what-is-reactive-programming#heading-what-is-a-data-stream) in JavaScript and TypeScript. It is based on the ReactiveX programming model, which allows developers to write asynchronous, event-driven, and data-centric code in a declarative style.

RxJS provides a rich set of operators that can be used to transform, filter, combine, and manipulate streams of data emitted by Observables. It also provides utility functions to create, merge, and control streams of data. RxJS can be used in various JavaScript environments, such as web browsers, Node.js, and mobile applications, and can be integrated with other libraries and frameworks, such as **Angular**, React, and Vue.

[Reactive programming](https://blog.multignite.com/what-is-reactive-programming) with RxJS can help simplify complex asynchronous code, reduce the amount of boilerplate code, and make it easier to handle errors and manage state.

## RxJS

RxJS is built on top of the concepts of Observables, Observers, and Subjects.

*   An Observable is a stream of data that can be observed over time.
    
*   Observers are functions that subscribe to an Observable to receive notifications whenever new data is available.
    
*   A Subject is a special type of Observable that can act as both a source of data and an Observer.
    

### Example in TypeScript

```javascript
import { Observable } from 'rxjs';

// Create an Observable that emits a sequence of numbers
const observable = new Observable((observer) => {
  observer.next(1);
  observer.next(2);
  observer.next(3);

  // Return a function to clean up resources when unsubscribed
  return () => console.log('Unsubscribed');
});

// Subscribe to the Observable
const subscription = observable.subscribe({
  next: (value) => console.log(value),
  complete: () => console.log('Sequence complete'),
});

// Unsubscribe after 2 seconds
setTimeout(() => {
  subscription.unsubscribe();
}, 2000);
```

This code creates an observable that emits a sequence of numbers (1, 2, and 3), and sets up a subscription to it. The subscription prints each emitted value to the console using the `next` handler, and prints 'Sequence complete' when the observable completes using the `complete` handler. The observable also returns a function that will log 'Unsubscribed' to the console when the subscription is unsubscribed.

Finally, the code sets a timer to unsubscribe the subscription after 2 seconds, which triggers the execution of the function that logs 'Unsubscribed' to the console.

## .subscribe()

The `subscribe` method is used to attach an observer to an observable, so that the observer can receive notifications of emissions from the observable. The `subscribe` method takes one or more functions as arguments, which define how the observer should handle different types of notifications. For example, you can define a `next` function to handle emissions of new values, a `complete` function to handle the completion of the observable, and an `error` function to handle any errors that occur.

When you call `subscribe`, it returns a subscription object, which represents the connection between the observer and the observable. You can use this subscription object to unsubscribe from the observable later, which stops the observer from receiving further notifications.

### Example in TypeScript

```javascript
import { of } from 'rxjs';

const observable = of(1, 2, 3); // Create an observable that emits the values 1, 2, 3

const subscription = observable.subscribe(
  (value) => console.log(value), // Define a function to handle each emission
  (error) => console.error(error), // Define a function to handle errors
  () => console.log('Observable completed') // Define a function to handle completion
);

// Later, when you want to unsubscribe
subscription.unsubscribe();
```

In this example, we create an observable that emits the values 1, 2, 3 using the `of` utility function. We then use the `subscribe` method to attach an observer to the observable, which prints each value to the console. We also define functions to handle errors and completion. Finally, we store the subscription object in a variable, so that we can unsubscribe from the observable later using the `unsubscribe` method.

## .unsubscribe()

The `unsubscribe` is a method used to detach an observer from an observable, which stops the observer from receiving further notifications. To unsubscribe from an observable, you need to call the `unsubscribe` method on the subscription object that was returned when you called `subscribe`.

Unsubscribing is important because it releases resources that were allocated to the observable, such as network connections or event listeners. If you don't unsubscribe, these resources may continue to be used even after the observable is no longer needed, which can lead to memory leaks and other issues.

### Example in TypeScript

```javascript
import { interval } from 'rxjs';

const observable = interval(1000); // Create an observable that emits a value every second

const subscription = observable.subscribe((value) => console.log(value)); // Subscribe to the observable and print each value to the console

setTimeout(() => {
  subscription.unsubscribe(); // Unsubscribe from the observable after 5 seconds
}, 5000);
```

In this example, we create an observable that emits a value every second using the `interval` utility function. We then use the `subscribe` method to attach an observer to the observable, which prints each value to the console. We store the subscription object in a variable, and then use the `setTimeout` function to unsubscribe from the observable after 5 seconds using the `unsubscribe` method.

## Subscription object

In RxJS, a `Subscription` is an object that represents the connection between an `Observer` and an `Observable`. When you call the `subscribe()` method on an `Observable`, it returns a `Subscription` object that allows you to manage the subscription and unsubscribe from the `Observable` when you no longer need to receive notifications.

The `Subscription` object has an `unsubscribe()` method that can be called to terminate the subscription and stop receiving notifications from the `Observable`. By unsubscribing from the `Observable`, you can free up resources and avoid memory leaks or unnecessary processing.

In addition to the `unsubscribe()` method, the `Subscription` object also provides other methods and properties that allow you to manage the subscription. For example, you can use the `closed` property to check if the subscription is currently active or has been unsubscribed. You can also use the `add()` method to add child `Subscriptions` to the parent `Subscription`, which can be useful for managing multiple subscriptions.

Overall, the `Subscription` object is an important part of the RxJS API that allows developers to control the lifetime of their `Observable` streams and avoid potential issues with memory leaks or unnecessary processing.

[More Operators](https://blog.multignite.com/operators-in-rxjs)

