Do RxJS observers always process all events submitted before the observable is completed?

Viewed 122

I want to make sure that all events, which were submitted before complete was invoked on the observable, are logged.

I'm aware that operators exist that stop emission of events (takeUntil, etc.) completely.

The question that I have is whether other operators exist which would lead to emissions not being sent if the complete on the subject is sent too 'early'. Are there cases where it would be beneficial to wait with the completion of the observable until the event was handled by the observer?

For example, are there situations (imagine any other RxJS operator instead of the delay) where the following code ...

const subj = new Subject<string>();

subj.pipe(delay(500))
    .subscribe((val) => {
      console.log(val);
      subj.complete();
    });

subj.next('1');    

... makes more sense than that ...

const subj = new Subject<string>();

subj.pipe(delay(500))
    .subscribe((val) => {
      console.log(val);       
    });

subj.next('1');
subj.complete();

... when the subject should only emit one value?

Or is completing the subject immediately after next always safe in such situations?

If there are other factors I'm not aware of (e.g. synchronous vs. asynchronous execution of code) please mention them as well.

1 Answers

In general,

subj.next('1');
subj.complete();

is safe. As far as I know, none of the existing RxJS operators use a completion to cancel/unsubscribe observables early.

That being said, I can easily create such an operator myself. switchMap will cancel currently running inner observables when it receives it's next emission. You could, for example, create a custom operator that unsubscribes and exists early when it receives a complete event.

If your worried about that, however, you're out of luck. No matter what workaround you imagine, I can probably write an operator that will ruin your code. For example filter(_ => false) will stop the 1 from being emitted before the complete in either of the two cases you've described.

In the end, you and your coworkers must write good code (and test!) and RxJS doesn't change that.

Related