I am using the following pattern a lot in my Angular application. I have an observable that comes from an RxJs BehaviourSubject that has to be initialised with a value from another observable. I'd like to use it in an async pipe. The only way I can achieve this is like so:
ngOnInit() {
this.notificationService
.getNotificationForOperationId(`${this.operation.operationId}`)
.subscribe((notification: Notification) => {
this.activitiesExists = notification?.activities;
});
}
then I subscribe to changes to that variable:
subscription = this.notificationService.notificationUpdated$
.subscribe(() => {
this.activitiesExists = true;
});
I use the variable in my template:
<ng-container *ngIf="activitiesExists">
...
</ng-container>
I'd rather use the variable with an async pipe like so:
<ng-container *ngIf="activitiesExists | async">
...
</ng-container>
but I don't know how to define the variable in on RxJs statement. I am aware of the startWith()
RxJs Operator, but it only accepts static values and not an observable.
I'd like to use something like this, but it seems it does not exist:
this.activitiesExists = this.notificationService.notificationUpdated$.pipe(
startWith(this.notificationService.getNotificationForOperationId(this.operation.operationId))
);
Is there any way to achieve this behaviour ?
concat
ing your 2 observables can work – Andrei