【问题标题】:rxjs publishReplay with windowTime parameter resetingrxjs publishReplay 与 windowTime 参数重置
【发布时间】:2021-04-22 21:49:27
【问题描述】:

我正在尝试限制订阅在 rxjs 中缓存的时间。以前缓存是使用pipe(publishReplay(1), refCount()) 完成的。在找到这个漂亮的answer 并阅读docs 之后,我发现可以通过将第二个参数传递给publishReplay 来限制这个缓存时间。 示例:publishReplay(1, 60 * 1000)

我试着做一个最小的例子:

<button (click)="test()">Test</button>

JS:

  urlofApi = "https://api.github.com/search/repositories?q=helloWorld";

  testX = this.http.get(this.urlofApi).pipe(
    tap(() => console.log("called")),
    publishReplay(1, 5),
    refCount()
  );

  constructor(private http: HttpClient) {}

  test() {
    const x = this.testX.subscribe();
  }

见:https://stackblitz.com/edit/angular-ivy-z7ecyn?file=src%2Fapp%2Fapp.component.ts

但是 reslt 在 5ms 后并没有被丢弃,而是无限期地保持。我错过了什么?

【问题讨论】:

    标签: rxjs


    【解决方案1】:

    经过3小时的调试,我找到了如下答案:https://stackoverflow.com/a/54957061

    我所要做的就是在末尾添加一个take(1)

    新示例:

      testX = this.http.get(this.urlofApi).pipe(
        tap(() => console.log("called")),
        publishReplay(1, 5),
        refCount(),
        take(1)
      );
    

    StackBlitz:https://stackblitz.com/edit/angular-ivy-tyrbdw?file=src%2Fapp%2Fapp.component.ts

    完整示例:

    import { Component, VERSION } from "@angular/core";
    import { publishReplay, refCount, take, tap } from "rxjs/operators";
    import { HttpClient } from "@angular/common/http";
    
    @Component({
      selector: "my-app",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent {
      name = "Angular " + VERSION.major;
    
      urlofApi = "https://api.github.com/search/repositories?q=helloWorld";
    
      testX = this.http.get(this.urlofApi).pipe(
        tap(() =>
          console.log(
            `++ api was newly called at ${new Date().toLocaleTimeString()} ++`
          )
        ),
        publishReplay(1, 5000),
        refCount(),
        take(1)
      );
    
      constructor(private http: HttpClient) {}
    
      test() {
        console.log("Requesting data from API");
        this.testX.pipe(take(1)).subscribe(() => console.log("completed"));
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多