如何从rxjs重构间隔以避免代码重复

时间:2019-04-10 00:12:16

标签: angular rxjs observable

我有以下代码显然需要改进。它使用间隔来发出重复的http get请求。是否有另一种rxjs方法来改进此代码?我在时间间隔之外发出第一个http请求的原因是,我注意到时间间隔首先延迟,然后用数据响应。因此,第一个请求避免了延迟。

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Weather } from './interface';
import { Observable } from 'rxjs';
import { concatMap } from 'rxjs/operators';
import { interval } from 'rxjs';
export class WeatherComponent implements  OnInit {
  weathers: any;
  response: any;

  private serviceUrl = 'https://api.weather.gov/gridpoints/OKX/36,38/forecast';
  n = 10000;
  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.response = this.http.get<Weather>(this.serviceUrl );
    this.response.subscribe(
      results => {
        this.weathers = results.properties.periods.slice(0, 2);
      });

    // 5 minute interval
    interval(5 * 60 * 1000).pipe(
      concatMap( () => this.http.get<Weather>(this.serviceUrl) ),
      ).subscribe(results => this.weathers = results.properties.periods.slice(0, 2));
  }

}

1 个答案:

答案 0 :(得分:1)

This answer已经为您的问题提供了答案,但是如果不正确地应用它,可能会导致其他问题,我将保留此答案。

重构如下:

import {Subscription, timer} from 'rxjs';

const MILISECS_IN_5_MINS = 5 * 60 * 1000;
export class FooComponent {
    private timerSub = Subscription.EMPTY;

    ...

    ngOnInit() {
      this.timerSub = timer(0, MILISECS_IN_5_MINS).pipe(
        concatMap(() => this.http.get<Weather>(this.serviceUrl))
        ).subscribe(results => this.weathers = results.properties.periods.slice(0, 2));
    }

    ngOnDestroy(){
      // Unsubscribe to avoid mem. leaks, as the timer stream is infinite
      this.timerSub.unsubscribe();
    }

    ...
  }