How to do polling in Angular using Rxjs?

Vikas Kohli
2 min readDec 6, 2019

--

Polling -> Process to check its readiness or in other words hit to the server again and again and when it's ready, handle the final data.

Example:- If I get true status from the server, then I need to show the user that processing is completed if not then processing still going.

We can do this polling in Angular using RxJs( Reactive Extensions for JavaScript) library.

I will hit the API using HttpClient and RxJs functions in Angular 7 and check whether the processing is done or not, in every 3 seconds, I am checking the status of processing, whether it's completed or not. If from the backend whenever I received the processing is done, then from that time, I’ll not hit API as the processing is completed.

Let's import the functions that need to use for polling.

import { concatMap, map, switchMap, filter, take} from 'rxjs/operators';
import { timer, BehaviorSubject } from 'rxjs';
import { HttpClient } from '@angular/common/http';

For hit API, need to import the HttpClient module.

const url$ = this.http.get('my-api-url');// api url 
this.loading$.pipe(
switchMap(_ => timer(0, 3000).pipe(
concatMap(_ => url$),
map((response: ServerResponse) => {
return response;
})
).pipe(filter(data => data.generated===true))
.pipe(take(1)
)
)
.subscribe(()=> {console.log('done')})

In the above functions, I am calling API every 3 seconds when the response gets done, then I am logging my status to ‘done’. ServerResponse is an interface that we are getting response type from the API.

Now I’ll combine the whole code in one file i.e ts file(logic file in Angular 2+ versions)

import { concatMap, map, switchMap, filter, take} from 'rxjs/operators';
import { timer, BehaviorSubject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
export interface ServerResponse{
generated: boolean
}
export class AppComponent implements OnInit {
loading$ = new BehaviorSubject('');
constructor(private http: HttpClient) { }ngOnInit() {
const url$ = this.http.get('my-api-url');
this.loading$.pipe(
switchMap(_ => timer(0, 3000).pipe(
concatMap(_ => url$),
map((response: ServerResponse) => {
return response;
})
).pipe(filter(data => data.generated===true))
.pipe(take(1))
)
)
.subscribe(()=> {console.log('done')})
}
ngOnDestroy(): void {
/**
* Unsubscribe all subscriptions to avoid memory leak
*/
//here will do unsubscribe
}
}

Now the above code does polling using RXJS functions. Another way, we can also use the `setInterval` function and then create a variable of name ‘isDone’ and set to false when processing going and that variable should be checked before hitting the API.

Happy Coding using RXJS with Angular. 😊

--

--

Vikas Kohli
Vikas Kohli

Written by Vikas Kohli

B.E Software Developer, Enthusiastic, Ego-surfing

No responses yet