DEV Community

Discussion on: What's the RxJs/ NgRx code bit that you are most proud of?

Collapse
 
oleksandr profile image
Oleksandr • Edited

My the-most-proud-code using RxJS is described in my article: medium.com/@alexanderposhtaruk/rx-...

In short:


@Injectable()
class HttpService {
    private retryLogicSubject: Subject < any > ;
    constructor(private http: HttpClient, private store: Store < any > ) {}
    ngOnInit() {
        this.store
            .map((state) => state.tokens)
            .subscribe((tokens) => {
                if (this.retryLogicSubject) {
                    this.retryLogicSubject.next({})
                }
            });
    }
    public getWithRetryLogic(url) {
        return Observable.defer(() => this.http.get(url, this.options))
            .catch((err) => {
                if (error.status === 401) {
                    return Observable.throw(error);
                }
                return Observable.of(error);
            })
            .retryWhen((error) => {
                this.retryLogicSubject = new Subject();
                this.startRefreshTokensProcess();
                return this.retryLogicSubject.asObservable()
            })
            .map(() => {
                if (data.status < 400 && data.status >= 200) { //check for errors
                    this.retryLogicSubject = undefined;
                    return data.json();
                }
                throw data; // back to error stream
            })
            .timeout(5000)
    }
    private startRefreshTokensProcess() {
        let data = { refreshToken: this.refreshToken }
        this.http
            .post('refreshTokenUrl', data)
            .subscribe(
                (data: Response) => this.saveTokensToStore(data.json()),
                (error) => this.getTokenFromParentAndSaveToStore()
            );
    }
}