Observables are a key feature of RxJS, a library for reactive programming in JavaScript. Observables represent a stream of data that can be subscribed and manipulated using RxJS operators. In this article, we will dive deep into RxJS observables, including what they are, how they work, and how to use them in an Angular application.
Observables can emit zero or more values and can optionally complete or throw an error. They are often used to represent events, asynchronous requests, or data sources.
Table of Contents
What are Observables in Angular?
In an Angular application, Observables are often used to manage HTTP requests, user interactions, or data sources. For example, Observables can be used to manage pagination, search suggestions, form validation, real-time chat, and more.
It is a sequence of data that can arrive asynchronously, in multiple pieces, and at different timings.
How Observables Work?
Observables have three important methods, subscribe()
, next()
, and complete()
. Here are more details:
subscribe()
: This method is used to start observing the stream of data emitted by the Observable. When a subscription is created, the Observable starts executing and emits values to the subscriber. The subscription can be closed by calling theunsubscribe()
method.next()
: This method is used to emit a new value in the Observable stream. When thenext()
method is called, the Observable emits the value to all its subscribers.complete()
: This method is used to indicate that the Observable has completed its emission of values. When thecomplete()
method is called, the Observable stops emitting values and notifies all its subscribers that it has completed.
Checkout my other articles on Angular programming.
Observable subscribe()
event example
subscribe()
: This method is used to start observing the stream of data emitted by the Observable. It takes up to three callback functions: next()
, error()
, and complete()
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import { Observable } from 'rxjs'; const observable = new Observable((observer) => { observer.next('Hello'); observer.next('StackBlogger'); observer.complete(); }); observable.subscribe( (value) => console.log(value), // next() callback (error) => console.error(error), // error() callback () => console.log('Completed') // complete() callback ); |
In the above example, we create an Observable that emits two values (‘Hello’ and ‘StackBlogger’) and then completes. We then subscribe to the Observable and pass in callback functions for next()
, error()
, and complete()
. When the Observable emits the ‘Hello’ value, the next()
callback is called with the value as its argument. The same thing happens with the ‘StackBlogger’ value. Finally, when the Observable completes, the complete()
callback is called.
Observable next()
event example
next()
: This method is used to emit a new value in the Observable stream. When the next()
method is called, the Observable emits the value to all its subscribers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import { Observable, Subject } from 'rxjs'; class ObservableExample { private subject = new Subject<string>(); setBlogName(name: string): void { this.subject.next(name); } getBlogName(): Observable<string> { return this.subject.asObservable(); } } const obsClass = new ObservableExample(); obsClass.getBlogName().subscribe((name) => { console.log('My Blog Name is', name); }); obsClass.setBlogName('StackBlogger'); |
In the above code, a class ObservableExample uses the RxJS library to implement an observable pattern. The class contains two methods:
setBlogName(name: string): void
: This method takes a string parametername
and emits it as the next value of a privatesubject
instance variable. Thenext
method is used to emit a new value on the subject.getBlogName(): Observable<string>
: This method returns anObservable
instance that is created from the privatesubject
variable using theasObservable
method. This ensures that the observable returned by this method can only be subscribed to, but not modified.
The code then creates an instance of the ObservableExample
class and subscribes to the observable returned by the getBlogName
method using the subscribe
method. The subscribe method takes a function as its argument, which will be called whenever a new value is emitted by the subject
.
Finally, the setBlogName
method is called to emit a new value on the subject
, which triggers the function passed to the subscribe
method to be called with the emitted value. In this case, the console will output “My Blog Name is StackBlogger”.
Observable complete()
event example
complete()
: This method is used to indicate that the Observable has completed its emission of values. When the complete()
method is called, the Observable stops emitting values and notifies all its subscribers that it has completed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import { Observable } from 'rxjs'; const observable = new Observable((observer) => { observer.next('Hello'); observer.next('StackBlogger'); observer.complete(); }); observable.subscribe({ next: (value) => console.log(value), complete: () => console.log('Completed') }); |
In the above example, we create an Observable that emits two values (‘Hello’ and ‘StackBlogger’) and then completes. We then subscribe to the Observable and pass in an object with a next()
and complete()
method. When the Observable emits the ‘Hello’ value, the next()
callback is called with the value as its argument. The same thing happens with the ‘StackBlogger’ value. Finally, when the Observable completes, the complete()
callback is called.
Conclusion
Do you want to know best ways to share data between Angular components using RxJS? Checkout the article here.
Overall, Angular RxJS Observables provide a powerful and flexible way to manage asynchronous data streams in Angular applications. They are a key part of reactive programming and are widely used in modern web development.
These methods in RxJS Observables can help you manage asynchronous data streams effectively in your Angular application. By using subscribe()
, next()
, and complete()
methods, you can observe and manipulate the stream of data emitted by the Observable.