0

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()),
        );

    }

1 Answer 1

1

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()),
            );

        }
Sign up to request clarification or add additional context in comments.

1 Comment

True, I was changing some things, and didn't realize that worked like that. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.