Yesterday I was discussing with a colleague the pro’s and con’s of Observable streams. One of the disadvantages is that you can end up with situations where you want to have multiple subscribers be aware of the same stream and share the stream in multiple contexts. This is a tricky situation not in the least because you have to be aware about the difference between hot and cold observables.
Today another colleague pointed me to the ‘async as else’ syntax as a great way to reduce the sharing of streams to a minimum. Here is a small code snippet he sent me:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Component({ | |
selector: 'app', | |
template: ` | |
<div *ngIf="users$|async as users; else loading"> | |
Number of users: | |
<users-grid [users]="users"></users-grid> | |
</div> | |
<ng-template #loading>Loading...</ng-template> | |
` | |
}) | |
class AppComponent { | |
// This stream will only subscribed to once | |
users$ = this.http.get(...); | |
} |