chaining observables with switchmap and forkjoin not working as expected angular typescript rxjs

Viewed 2001

im currently creating trying to create a system where if i successfully updated a request i trigger 3 observables in a forkjoin then once those are finished console.log('complete/or finish') otherwise if it is not do nothin. currently though the observables are completing before the forkjoin is complete and im completely at a loss of what's happening,

  copyAttachments(): Observable<any> {
    if (this.model.attachments.length > 0) {
      return this.attachmentService.copyAttachments(this.model.attachments, this.model.id);
    }
    return empty();
  }

  uploadAttachments(): Observable<any> {
    this.showAttachmentsUploadingModal = true;
    const formData = new FormData();

    if (this.formAttachments.length > 0) {
      this.showAttachmentsUploadingModal = true;
      this.formAttachments.forEach(file => {
        formData.append('files', file, file.name);
      });
    }

    // uploading empty formData will still trigger creation of default folder structure
    return this.attachmentService.uploadAttachments(formData, this.model.id);
  }

  uploadCustomerData(): Observable<any> {
    this.showAttachmentsUploadingModal = true;
    const formData = new FormData();

    if (this.formCustomerData.length > 0) {
      this.showAttachmentsUploadingModal = true;
      this.formCustomerData.forEach(file => {
        formData.append('files', file, file.name);
      });
      return this.attachmentService.uploadCustomerData(formData, this.model.id);
    }

    return empty();
  }

handleAttachments(): Observable<any> {
    return forkJoin
      (
        this.copyAttachments(),
        this.uploadCustomerData(),
        this.uploadAttachments()
      )
  }

  updateRequest() {
    this.myservice
      .updateRequest(this.model)
      .pipe(
        switchMap((saveResult: boolean) => {
          this.showSubmittingModal = false;
          if (saveResult === true) {
            return this.handleAttachments();
          } else {
            return empty();
          }
        }),
      )
      .pipe(finalize(() => {
        console.log('finish')
      }))
      .subscribe(
        response => {
          // todo: do anything with this response from uploadAttachments()?
          this.showAttachmentsUploadingModal = false;
        },
        error => {
          location.reload();
        },
        () => {
          console.log('complete')
        }
      );
  }

the expected result is my service completes, then my forkjoin observables complete then it will console.log('finish')

currently the result is the service completes. it console.logs('finish') then my forkjoin triggers

1 Answers

The solution I found to this problem is instead of returning empty() or of() you need to return an empty object as an observable this way Forkjoin still maintains value so return of({}) and everything is fine

Related