rxjs processing http request timeout

Keywords: network angular

Original blog address

Usage scenarios

The user requests an operation in the background and does not respond for a long time. We want to give the user an information display (request timeout, bad network...) .

RxJS implementation

About RxJS Here

My implementation of this function mainly uses two operators: delay and race.
*Delay delays the sending of the source Observable by a given timeout or until a given time. Delay time (in milliseconds) or Date object (send delay to this point in time).
*race returns the Observable, which is the image of the first outgoing item in the combination of source Observable and provided Observables.

The specific implementation process code (using annualr and ionic) is as follows:
I encapsulated it into a service for easy use. Mainly look at the timeoutDeal method.
service.ts

import { Injectable } from "@angular/core";
import { delay, map, race } from "rxjs/operators";
import { Observable } from "rxjs/Observable";
import { AlertController, LoadingController } from "ionic-angular";

@Injectable()
export class HttpTimeoutService {
    loading: any;
    timer: any;
    timers:any[]=[];
    constructor(private loadingCtrl: LoadingController,
                private alertCtrl: AlertController) {
    }

    // **parameter name And parameters mes identical
    showLoading(name) {
        const self = this;
        let obj={name:name,timer:undefined,loading:undefined};
        const timer = setTimeout(() => {
            let loading = this.loadingCtrl.create();
            loading.present();
            obj.loading=loading;
        }, 500);
        obj.timer=timer;
        this.timers.push(obj);
    }

    clearTimer(name) {
        const self = this;
        for(let i=0;i<this.timers.length;i++){
            if(this.timers[i].name===name){
                if(this.timers[i].loading){
                    this.timers[i].loading.dismiss();
                }
                clearTimeout(this.timers[i].timer);
                this.timers.splice(i,1);
                return;
            }
        }
    }

    timeoutDeal(mes) {
        const self = this;
        let TIME_OUT = 6000;
        let cancel$ = Observable.of(null).pipe(delay(TIME_OUT),
            map(_ => {
                // throw 'error';

                self.clearTimer(mes);
                self.alertCtrl.create({
                    title: 'connection timed out',
                    message: 'The current network is not stable, please find a stable network!',
                    buttons: ['Determine']
                }).present();
                throw mes + 'timeout!'
            }));
        return cancel$;
    }

}

Pipe is a built-in pipe method in Observable (Observable.prototype.pipe), which can combine operators in a way similar to the previous chain call. After rxjs version 5.5.

Posted by mattkirkey on Thu, 02 Jan 2020 14:46:42 -0800