【问题标题】:How to refactor interval from rxjs to avoid code duplication如何从 rxjs 重构间隔以避免代码重复
【发布时间】:2019-04-10 00:12:16
【问题描述】:

我有以下显然需要改进的代码。它使用间隔发出重复的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));
  }

}

【问题讨论】:

标签: angular rxjs observable


【解决方案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();
    }

    ...
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 2014-03-07
    相关资源
    最近更新 更多