In this blog, I'm going to explore the use of RxJS operators. As a beginner developer, we hear a lot about Promise/Observables/Subscription to call asynchronous services and perform data operations using traditional means, such as - loops, custom property mapper, and class models and so on. Instead, we can use various RxJS operators which are very easy and simple to write. In this blog, I will be demonstrating some of the real-time use cases of our day to day work and handling complex response in an easy way.
of() is used for converting the string/objects to Observables.
- import { Observable, of, from } from 'rxjs';
- ngOnInit() {
- const employee = {
- name: 'Rajendra'
- };
- const obsEmployee: Observable<any> = of(employee);
- obsEmployee.subscribe((data) => { console.log(data); });
- }

- ngOnInit() {
- const employee = {
- name: 'Rajendra'
- };
- const obsEmployee: Observable<any> = of('Rajendra Taradale');
- obsEmployee.subscribe((data) => { console.log(data); });
- }
- import { map } from 'rxjs/operators';
- ngOnInit() {
- const data = of('Rajendra Taradale');
- data
- .pipe(map(x => x.toUpperCase()))
- .subscribe((d) => { console.log(d); });
- }

- import { share} from 'rxjs/operators';
- getPosts(): Observable<any[]> {
- return this.http.get<any[]>('https://jsonplaceholder.typicode.com/users'));
- }
- setLoading(obs: Observable<any>) {
- this.loading = true;
- obs.subscribe(() => this.loading = false);
- }
- ngOnInit() {
- const request = this.getPosts();
- this.setLoading(request);
- request.subscribe(data => console.log(data));
- }

- getPosts(): Observable<any[]> {
- return this.http.get<any[]>
- ('https://jsonplaceholder.typicode.com/users').pipe(share());
- }
- getUsers(): Observable<any[]> {
- return this.http.get<any[]>('https://jsonplaceholder.typicode.com/users');
- }
- getPosts(): Observable<any[]> {
- return this.http.get<any[]>('http://jsonplaceholder.typicode.com/posts');
- }
- ngOnInit() {
- const reqPosts = this.getPosts();
- const reqUsers = this.getUsers();
- const reqPostsUser = reqPosts.pipe(
- switchMap(posts => {
- return reqUsers.pipe(tap(users => {
- console.log('Posts List ', posts);
- console.log('User List ', users);
- }));
- })
- );

DebounceTime and DistinctUntilChanged
- this.personalForm.get('firstName').valueChanges.pipe(debounceTime(500)).subscribe(
- value => {
- console.log(value);
- }
- );
- this.personalForm.get('firstName').valueChanges.pipe(distinctUntilChanged()).subscribe(
- value => {
- console.log(value);
- }
- );
- import { Subscription } from 'rxjs';
- Request: Subscription;
- CallSErvice() {
- if (this.Request != null && !this.Request.closed) {
- this.Request.unsubscribe();
- }
- this.Request = this.getUsers().subscribe();
- }
Here is another ready-made feature to unsubscribe all observables.
These operators are just another way to handle or manage your observables data and take and ignore the requests accordingly
We will play with the below code to demonstrate other operators.
- import { Observable, of, from, Subscriber, Subscription, fromEvent, Subject } from 'rxjs';
- import { map, share, switchMap, tap, count, first, takeUntil} from 'rxjs/operators';
- const eventSource= fromEvent(document, 'click');
- eventSource.subscribe(()=>{
- console.log('clicked ', this.count);
- this.count++;
- });
- const eventSource= fromEvent(document, 'click');
- eventSource.pipe(first()).subscribe(()=>{
- console.log('clicked ', this.count);
- this.count++;
- });

- const eventSource= fromEvent(document, 'click');
- eventSource.pipe(takeWhile(()=> this.count < 3)).subscribe(()=>{
- console.log('clicked ', this.count);
- this.count++;
- });

- const eventSource= of(1, 2, 3, 4, 5);
- eventSource.pipe(takeLast(2)).subscribe((d)=>{
- console.log('Get last Value ',d);
- });

TakeUntil() is useful when you are working with other observables, and based on other observables you emit a value on start, and stop the emitted values
- startClick = new Subject<void>();
- const eventSource = fromEvent(document, 'click');
- eventSource.pipe(takeUntil(this.startClick)).subscribe(() => {
- console.log('clicked ');
- });
- stopClick() {
- this.startClick.next();
- this.startClick.complete();
- }
- const reqPosts: Observable<any> = this.getPosts();
- const reqUsers: Observable<any> = this.getUsers();
- const dt: Observable<any> = reqPosts.pipe(
- mergeMap(post=>{
- return reqUsers.pipe(
- map(user=>{
- const allData = {
- rpost:post,
- ruser:user
- };
- return allData;
- })
- )
- })
- )
- dt.subscribe((dt)=>console.log(dt));

- const reqPosts: Observable<any> = this.getPosts();
- const reqUsers: Observable<any> = this.getUsers();
- const combinedData = forkJoin(reqPosts, reqUsers);
- combinedData.subscribe(dt => console.log(dt));


Laxmidhar SahooPosted Jan 3, 2019, 10:53 PM
Thanks for the article .It is use full