How can I avoid multiple nested subscriptions using RxJS operators?

前端 未结 4 1616

I am working on a file encryption and upload class using Angular. Many of these operations are async and therefore the methods I wrote are returning RxJS Observables.

<
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 04:23

    You can use mergeMap and filter operators from RxJs and chain your calls. You will need to create some function level variables to use during the chaining.

    import { mergeMap, filter, catchError } from 'rxjs/operators`
    
    public upload(file) {
        const gen = this.indexGenerator(); // generator function
        let range, token;
        this.prepareUpload(file)
          .pipe(
            mergeMap((values) => {
              const [response, filekey, data] = values;
              token = response.token;
              return this.encryptData(data, filekey);
            }),
            mergeMap(encryptedDataContainer => {
              const formData = this.prepareEncDataUpload(encryptedDataContainer.data, file.name)
              range = this.getRange(file.size, gen.next().value);
    
              return this.uploadEncryptedData(formData, token, range);
            }),
            filter(() => !!range.isFinalPart),
            mergeMap(() => {
              return this.completeUpload(encryptedDataContainer.updatedFilekey, token);
            })
            catchError((error) => {
              console.log(error);
              // handle the error accordingly.
            })
          )
          .subscribe(() => {
            console.log('success');
          });
    
      }
    

提交回复
热议问题