DeployU
Interviews / Frontend Engineering / What is RxJS and how is it used in Angular?

What is RxJS and how is it used in Angular?

conceptual RxJS Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are building a new feature that needs to handle a stream of real-time data from a WebSocket.

You need to find a way to process the data as it comes in, and you are considering using RxJS.

The Challenge

Explain what RxJS is and how it is used in Angular. What are the key concepts of RxJS, and how would you use them to solve this problem?

Wrong Approach

A junior engineer might not be aware of RxJS. They might try to solve this problem by using a series of callbacks, which would be difficult to read and maintain.

Right Approach

A senior engineer would know that RxJS is the perfect tool for this job. They would be able to explain what RxJS is and how to use it to handle a stream of real-time data.

Step 1: Understand What RxJS Is

RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code.

Step 2: The Key Concepts of RxJS

ConceptDescription
ObservableAn Observable is a stream of data that can be subscribed to.
ObserverAn Observer is an object with next(), error(), and complete() methods that is used to subscribe to an Observable.
OperatorAn Operator is a function that can be used to transform, filter, or combine Observables.
SubscriptionA Subscription represents the execution of an Observable. It can be used to unsubscribe from an Observable.

Step 3: How RxJS is Used in Angular

RxJS is used extensively in Angular for a variety of tasks, such as:

  • HTTP requests: The HttpClient in Angular returns an Observable that can be used to handle the response from an HTTP request.
  • Forms: The FormControl in Angular has a valueChanges property that is an Observable that can be used to listen for changes to the value of a form control.
  • Routing: The Router in Angular has an events property that is an Observable that can be used to listen for routing events.

Step 4: Solve the Problem

Here’s how we can use RxJS to handle the stream of real-time data from the WebSocket:

import { webSocket } from 'rxjs/webSocket';

const subject = webSocket('ws://localhost:8081');

subject.subscribe(
  (msg) => console.log('message received: ' + msg),
  (err) => console.log(err),
  () => console.log('complete')
);

subject.next(JSON.stringify({ op: 'hello' }));

In this example, we use the webSocket function from RxJS to create an Observable that represents the WebSocket connection. We then subscribe to the Observable to receive the data as it comes in.

Practice Question

You want to make two HTTP requests in parallel and then do something with the results of both requests. Which of the following would you use?