当数组为空时从(Array <observables>)处理rxjs

时间:2019-05-14 23:26:00

标签: typescript rxjs

鉴于打字稿中的以下函数返回一个可观察对象并接收一个可观察对象数组,我如何以一种更为优雅的方式删除第一个if,该对象检查该数组是否为空,以便观察该对象完成时,在函数上调用subscribe()。

我实现了if。但是看起来很丑。

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 个答案:

答案 0 :(得分:1)

from([])将立即完成可观察性,因此后续运算符将不会执行。可以跳过长度检查

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

        }