dagda1
dagda1

Reputation: 28840

not able to cancel observable from rxjs 5.0

I have this function:

 uploadFiles(files: FileToUpload[]) {
    return Observable.create(async (observable) => {
      const aborters: Aborter[] = [];

      for (const fileToUpload of files) {
        let uploadResponse: UploadResponse;

        const aborter = Aborter.none;

        aborters.push(aborter);

        try {
          uploadResponse = await this.upload(file)
        } catch (err) {
        }
      }

      return () => {
        console.log('coooo');

        this.files$.next([]);

        for (const aborter of aborters) {
          if (!aborter.aborted) {
            aborter.abort();
          }
        }
      };
    });
  }

I want this observable to be cancellable when the user navigates awwy from the apge if there is a download happening so I am returning a function that is called when unsubscribe calls.

I then subscribe like this:

this.uploadSubscription = this.uploadService.uploadFiles(this.control.value).subscribe(
      () => console.log('progress'),
      (e) => {
        console.log(`errored with ${e}`);
        this.uploadSubscription.unsubscribe();
      },
      () => {
        console.log('completed');
        this.uploadSubscription.unsubscribe();
      }
    );

And I have an ngOnDestroy like this:

ngOnDestroy() {
    if (this.uploadSubscription) {
      this.uploadSubscription.unsubscribe();
    }
  }

But even though the unsubscribe method is called, the callback returned from Observable.create is not called.

Upvotes: 0

Views: 20

Answers (1)

martin
martin

Reputation: 96949

I think the problem is that from the Observable.create callback you're in fact returning a Promise and not a teardown method.

You marked the callback with async keyword so it returns a Promise so when you later call return () => {} you're actually returning Promise<() => void> so it's never invoked. Not even when you call unsubscribe.

You'd have to restructure the chain in order to make it unsubscribable depending on what you want to do but it seems like you might not even need to use await because you never push any notifications to the observer.

Upvotes: 1

Related Questions