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? 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.