简体   繁体   English

如何跟踪数据是否以完全反应方式加载?

[英]How to track if data has been loaded in fully reactive way?

Consider following code 考虑以下代码

 heroes: Obserable<Hero[]>;
 private _loadHeroes: EventEmitter<void> = new EventEmmiter;

 constructor(heroService: HeroService) {
    this.heroes = _loadHeroes.switchMap(() => heroService.fetchHeroes());
 }

Does anyone have any clue how without doing manual subscription to add something like heroesLoaded: BehaviorSubject<boolean> in a proper reactive way? 没有人知道如何通过手动订阅以适当的反应方式添加诸如heroesLoaded: BehaviorSubject<boolean>类的东西吗? Sure I could do something like 当然可以做类似的事情

    this.heroes = _loadHeroes.switchMap(() => {
      this.heroesLoaded.next(false)
      heroService.fetchHeroes().finally(() => this.heroesLoaded.next(true)
    });

But I believe this not the best way of doing it, the idea is to leave all subscriptions to async pipe and do everything only in streams. 但是我认为这不是最好的方法,其想法是将所有订阅留给异步管道,并且仅在流中完成所有操作。 Also I don't want to write it using impure side effects as described above. 我也不想使用如上所述的不纯净的副作用来编写它。 I tried looking towards pulishBehavior operator, but I don't see how I can use it to react to both moment of subscription and moment of value emmitting/error. 我尝试使用pulishBehavior运算符,但是我看不到如何使用它来响应订阅时刻和价值体现/错误时刻。 Is it possible at all? 有可能吗? I am interested in any possible solution that would be at least better, not necessarily perfect. 我对至少可能更好,不一定完美的任何可能的解决方案感兴趣。

If you just want to keep track of whether they are loaded (eg to show a loading indicator): 如果您只想跟踪它们是否已加载(例如,显示加载指示器):

heroes: Obserable<Hero[]>;
heroesLoaded: boolean = false;

constructor(heroService: HeroService) {
   this.heroesLoaded = false;
   this.heroes = of(null).pipe(
       tap(() => this.heroesLoaded = false),
       flatMap(() => heroService.fetchHeroes()),
       finalize(() => this.heroesLoaded = true)
   );
}

You could make heroesLoaded an BehaviorSubject if you want and replace the line this.heroesLoaded = false with this.heroesLoaded.next(false) - I don't see what advantages that would bring but the principle of using tap and finalize would be the same. 如果需要,可以使heroesLoaded一个BehaviorSubject并用this.heroesLoaded.next(false)替换this.heroesLoaded = false行-我不知道会带来什么好处,但是使用tap和finalize的原理是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM