【问题标题】:Rxjs way to let caller know method is complete, and to cache that resultRxjs 方法让调用者知道方法已完成,并缓存该结果
【发布时间】:2018-09-07 03:33:48
【问题描述】:

长话短说:我有一个 Angular 应用程序通过调用一个服务来初始化,该服务调用另一个数据服务。中间服务从数据服务接收并处理其数据后,它必须通过 Observable 或 Subject 与应用程序通信,应用程序才能继续加载。我想短路对同一方法的任何后续调用。

export class MiddleService {
    private triedOnce = false;
    private isLoadedSubject = new AsyncSubject();

    public loadConfig (): AsyncSubject<any> {
        if (!this.triedOnce) {
            this.isLoadedSubject.next(false);
            this.dataService.getConfiguration(...).subscribe(
                (data) => {
                    // do stuff with data
                    this.isLoadedSubject.next(true);
                }
            );

            this.isLoadedSubject.complete();
            this.triedOnce = true;
        }
        return this.isLoadedSubject;
    }
}

我想,第一个问题是使用这样的主题是否是反模式或非标准使用。 (Does this apply?)

其次,我觉得我应该重用并且能够重用 isLoadedSubject 而不是需要单独的布尔值。我不确定如何在订阅及其complete 回调之外执行此操作。 AsyncSubject 有一个 isCompleted 属性,但它是私有的。

【问题讨论】:

  • Rx 的方式是什么都不做。出于某种原因,Rx 是一元函数式语言。只需使用 .publish() 将热的 observable 转换为冷的。

标签: angular rxjs rxjs6


【解决方案1】:

我会这样做:

export class MiddleService {
   public readonly config$ = this.dataService.getConfiguration(...)
        .pipe(shareReplay(1));
}

这将延迟获取配置,并将缓存它以供所有后续调用。

另请参阅:Angular 5 caching http service api calls

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 2010-12-14
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多