0

I'm experimenting with Angular 2 and caching of values received from backend services. I've noticed that I came to the following pattern - using BehaviorSubject with undefined initial value and filter it to postpone display of controls dependent on values received from backend.

private _lazyValue: BehaviorSubject<ILazyValue> =
    new BehaviorSubject<ILazyValue>(undefined);

get lazyValue(): Observable<ILazyValue> {
  return this._lazyValue.filter(val => val !== undefined);
}

Inside template:

<div *ngIf="lazyValue | async; else nolv; let lv">
  <app-some-control [lazy_value]="lv"></app-some-control>
</div>
<ng-template #nolv>
  <span>Loading...</span>
</ng-template>

Question: are there any shortcuts for this somewhat fishy expression:

this._lazyValue.filter(val => val !== undefined)

Do I misuse BehaviorSubject somehow?

Minor Threat
  • 2,025
  • 1
  • 18
  • 32

1 Answers1

2

You can write it like this:

this._lazyValue.filter(Boolean)

That looks more clean.

But it seems you don't need to be using BehaviorSubject at all and use ReplaySubject(1) instead.

martin
  • 93,354
  • 25
  • 191
  • 226