rxjs主题/平面图做得对

时间:2016-12-09 10:04:55

标签: angular rxjs

这是我的代码很好用。我调用subject.next(),它发送到HTTP请求流,而HTTP请求流又发出HTTP响应。我相信沼泽标准模式。 Catch提供了我想要的错误处理。

我唯一的问题......可以简化吗?

let subject = new Subject<string>();

let httpStream$ = return subject.asObservable().flatMap((emit: any) => {

  return this.http[method](url, emit, this.options)
    .timeout(Config.http.timeout, new Error('timeout'))
    // emit provides access to the data emitted within the callback
    .map((response: any) => {
      return {emit, response};
    })
    .map(httpResponseMapCallback)
    .catch((err: any) => {
      return Observable.from([err.message || `${err.status} ${err.statusText}`]);
    });
}).publish().refCount();

我可以使用......

向主体发射
subject.next(dataToEmit);

我可以照常订阅httpStream $。

正如我所说,一切正常,但我做得对吗?有更简单的方法吗?

1 个答案:

答案 0 :(得分:1)

编码工作时,建议不多。我猜您正在使用主题,因为您需要能够手动&#34;刷新&#34; HTTP请求。

我只是建议三件事:

  • 您不需要使用asObservable()。对象已经充当了Observable。当您想要公开Observable(从方法返回)但隐藏您在内部使用Subject的事实时,asObservable()非常有用。由于您未归还主题,因此您无需使用asObservable()

  • 您永远不需要一个接一个地使用两个map()运算符:

    .map((response: any) => {
      return httpResponseMapCallback({emit, response});
    })
    
  • 您可以使用share()代替.publish().refCount(),而不是public class Program { /** * Prints the list of numbers from desde to hasta such that the righmost * digit of the sum of previous digits equals current digit, and that * happens for all digits * * Prints a 2nd line with as many underscores as characters contains the 1st * line * * If desde < 10 o the parameters make no sense, prints Err __ * * * @param desde * int from (included) * @param hasta * int to (included) * @return void */ public static void sumDigitsConsecutius(int desde, int hasta) { int suma = 0; int numeroSuma = 0; for (int i = desde; i <= hasta; i++) { int longitud = lenght(i); int posicion = longitud - 1; int contador = 0; for (double numComparar = posicioNumber(i, posicion); posicion > 0; posicion--) { numeroSuma = posicioNumber(i, lenght(i)); suma = suma + numeroSuma; if (suma != numComparar) { break; } else { numeroSuma = posicioNumber(i, (lenght(i) - 1)); contador++; } } if (contador == longitud - 1) { System.out.println(i); } } } /** * With this method i can calculate the length of a number */ public static int lenght(int numero) { int contador = 0; while (numero > 0) { contador++; numero = numero / 10; } return contador; } public static int posicioNumber(int numero, int posicio) { // Digit of n in position p int x; // Remove right digits from position p. x = numero / (int) Math.pow(10, posicio - 1); // Get the last digit. x = x % 10; return x; } public static void main(String[] args) { sumDigitsConsecutius(80, 120); } }