Questions
What is RxJS and how is it used in Angular?
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?
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.
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
| Concept | Description |
|---|---|
| Observable | An Observable is a stream of data that can be subscribed to. |
| Observer | An Observer is an object with next(), error(), and complete() methods that is used to subscribe to an Observable. |
| Operator | An Operator is a function that can be used to transform, filter, or combine Observables. |
| Subscription | A 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
HttpClientin Angular returns anObservablethat can be used to handle the response from an HTTP request. - Forms: The
FormControlin Angular has avalueChangesproperty that is anObservablethat can be used to listen for changes to the value of a form control. - Routing: The
Routerin Angular has aneventsproperty that is anObservablethat 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?