Reputation: 441
Given the following function, in typescript, that returns an observable and receives an Array of Observables, how can I, in a more elegant way, remove the first if, that checks if the array is empty, in order for the observable to complete, when called subscribe() on the function.
I implemented the if. But it looks ugly.
perform_scan_session_uploads(scan_operations: Array<Observable<any>>): Observable<any> {
// TODO: Check the errors in this inner observable.
if (scan_operations.length === 0) {
return of([true]);
}
return from(scan_operations).pipe(
concatAll(),
toArray(),
switchMap((result) => this.send_devices(result)),
switchMap((result) => this.check_device_errors(result)),
tap(() => {
console.log('Scan Errors: ', this.scan_errors);
}),
tap(() => this.clean_scan_session_data()),
);
}
Upvotes: 0
Views: 407
Reputation: 11345
from([])
will immediately completes the observable so the subsequent operators won't execute. it's fine to skip the length checking
perform_scan_session_uploads(scan_operations: Array<Observable<any>>): Observable<any> {
return from(scan_operations).pipe(
concatAll(),
toArray(),
switchMap((result) => this.send_devices(result)),
switchMap((result) => this.check_device_errors(result)),
tap(() => {
console.log('Scan Errors: ', this.scan_errors);
}),
tap(() => this.clean_scan_session_data()),
);
}
Upvotes: 1