Web / RxJs Interview questions
RxJS stands for Reactive Extension for JavaScript. RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code.
RxJS handles asynchronous data streams. It helps you to write programs against async data streams easily.
An Observable is basically a function that can return a stream of values to an observer over time, this can either be synchronously or asynchronously. The data values returned can go from zero to an infinite range of values.
Observer executes some instructions when there is a new value or a change in data values from Observable. The Observable is connected to the observer who does the execution through subscription, with a subscribe method the observer connects to the observable to execute a code block.
Get the subscription object when you subscribe and then call the unsubscribe method on the subscription object.
There are 2 types of observables: hot and cold. The main difference is that a cold observable creates a data producer for each subscriber, whereas a hot observable creates a data producer first, and each subscriber gets the data from one producer, starting from the moment of subscription.
A cold observable starts producing data when some code invokes a subscribe() function on it.
A hot observable produces data even if no subscribers are interested in the data.
use "npm install rxjs" command.
RXJS. | Promise. |
Observable return stream of data. | Promise return single value. |
You can subscribe and unsubscribe stream. | You cannot cancel a promise. |
An Observable only starts if you subscribe to it. This is why Observables are called lazy. | Promise starts immediately. |
Subscribe method is used for error handling which makes centralized and predictable error handling. | push errors to the child promises. |
Provides chaining and subscription to handle complex applications. | Uses only .then() clause. |
Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable, it doesn't matter if you want to handle 0, 1, or multiple events.
When you make some API calls using http clients returns Observables which we will subscribe to and get response/error.
map transforms data in an Observable into different format.
filter allow the data that meets condition/ restrict otherwise.
merge operator will combine multiple Observables into one. If one of the observables emit a value the combined one will emit as well.
concat only when observable completes, it will start with the next observable.
from operator will convert array/promise or iterable into a Observable.
debounceTime discard emitted values if a certain time didn't pass between the last input.
distinctuntilchanged only emits a value if it is different than the last one.
pluck select a property to emit.
delay emits a value with a delay.
Imperative programming means that the listener code (Observer) is responsible to pull stream of data. Reactive programming means you register a callback and the stream is responsible to push data.
Observer is an interface for a consumer of push-based notifications delivered by an Observable.
It has below structure,
interface Observer<T> { closed?: boolean; next: (value: T) => void; error: (err: any) => void; complete: () => void; }
A handler that implements the Observer interface for receiving observable notifications will be passed as a parameter for observable as below.
myObservable.subscribe(myObserver)
RxJS provides creation functions for the process of creating observables from promises, events, timers and even Ajax requests.
Multicasting is the practice of broadcasting to a list of multiple subscribers in a single execution.
In RxJS observables are cold, or unicast by default.
The "tap" operator is used to perform side-effects for notifications from the source observable. Used when you want to affect outside the state with a notification without altering the notification.
import { of } from 'rxjs'; import { tap } from 'rxjs/operators'; const source = of(1, 2, 3, 4, 5) source.pipe( tap(n => { if (n > 3) { throw new TypeError(`Value ${n} is greater than 3`) } }) ) .subscribe(console.log);
You can handle errors by specifying an error callback on the observer instead of relying on try/catch which are ineffective in asynchronous environment.
For example, you may define the error callback as below.
myObservable.subscribe({next(num) {console.log("next value:" + num)}, error (err) {console.log("Received error:" + err)} });
The subscribe() method can accept callback function definitions inline, for next, error and complete handlers is the short hand notation or subscribe method with positional arguments.
For example, you can define subscribe method as below.
myObservable.subscribe(num => console.log("next value:" + num), err=> console.log("Received error:" + err), () => console.log("Observer got a completed notification") );