I have an array of items that I turn into an observable using the of
function.
I create the observable before populating the array.
However, when the array is finally populated, the callback provided to subscribe
does not execute.
As far as I know, the observable
only triggers the callback
for the items already present in the list, which seems redundant to me.
In a scenario where I use this observable within an *ngFor
with the async
pipe, it works correctly. But when I pass the observable as a data source
to a mat-table
or if I provide my own callback
to the subscribe
function, nothing happens when the list is eventually populated.
What exactly does the async
pipe do behind the scenes that I might be overlooking?
export class DiscoveryService {
private deviceList: DeviceModel[] = [];
constructor() {
}
getDeviceList(): void {
// Fetch devices from server and add them to the deviceList
}
observeDeviceList(): Observable<DeviceModel[]> {
return of(this.deviceList);
}
}
export class DeviceListComponent implements OnInit {
deviceList$: Observable<DeviceModel[]>;
constructor(private discoveryService: DiscoveryService) { }
ngOnInit() {
this.deviceList$ = this.discoveryService.observeDeviceList();
// The callback here only runs once initially, with an empty list
this.deviceList$.subscribe(devices => console.log('got devices: ' , devices));
// After fetching devices from the server, the above subscription callback does not trigger again
this.discoveryService.getDeviceListx();
}
}
The async
pipe updates correctly, possibly because ngOnInit
is called before *ngFor
executes. This aspect is still uncertain to me.
<mat-nav-list *ngFor="let device of deviceList$ | async">