How I did my first polling
I’ve been working as a frontend developer at hibob for 2 years now and truly enjoy working on such a complex product.
I was recently tasked with creating a benefits product in our system, and want to share with you how I ended up doing this in bob.
To start, I needed to create a polling mechanism. The timer for that polling was controlled by the server, and the client was responsible for handling the response and triggering the correct event according to the response.
I decided to use observables streams.
Each response will trigger the next event/error in case something wrong happened in the process.
Let’s see some code :)
First I have created a stream of `status` that will trigger a promise function awaiting our server.
status$: Subject<PollingStatusEvent> = new Subject()interface PollingStatusEvent {
status: string;
description: string;
}// Now let's define the number of time the client will try to receive an answer: const INTERVAL_RETRIES = 12;And at last an enum to indicate Success or still in progress. Convention that agreed with the server.enum PollStatus {
success = 'Success',
inProgress= 'InProgress'
}
In addition success function `ourSuccessFunction` And error function `errorHandler`
public statusProvider(id: string): void {
this.status$
.pipe(take(INTERVAL_RETRIES))
.subscribe(
() => {
this.apiService.status(id)
.then((status) => {
switch (status) {
case PollStatus.success:
this.ourSuccessFunction(); // triggring success
break;
case PollStatus.inProgress:
this.status$.next(status); // triggring new event
break;
}
})
.catch(error => this.errorHandler(error, errorState));
},
error => this.errorHandler(error, errorState),
() => this.completeFunction()
);
this.status$.next(); // init the first event
}
After we are all done don’t forget to unsubscribe from our observable.
And that’s it my first polling, hope you enjoy :)