0

I implemented an RxJS architecture based on the answer to this question: Pipe RxJS observable to existing subject

Later, I noticed that the observable randomly closed and I've spent a lot of time to find the cause. In the end, appeared that this snippet was causing the closing:

const delayed = Observable.of(arr.shift()).delay(1000);
merge(otherObs, delayed).subscribe(mySubject);

The of/delay observable was completing after 1 second, and it piped the completion to mySubject, making it unable to receive other values, including the ones sent by otherObs in case they arrived after the timeout.

Here is a StackBlitz that shows the problem.

How can I avoid mySubject completes, without explicitly writing the callbacks?

8
  • can you show your otherObs ? ... if it's not completed you would'nt receive the complete notification
    – bubbles
    Sep 2, 2020 at 15:39
  • @bubbles I don't think that seeing otherObs makes the difference, since it's the delay that completes. In my case, otherObs is a custom observable that never completes for sure, but you can imagine it as a timer if you prefer it for reproduction Sep 2, 2020 at 15:49
  • interval, sorry, not timer Sep 2, 2020 at 15:59
  • @bubbles I added a StackBlitz Sep 2, 2020 at 16:00
  • from your stackblitz you're subscribing twice to the subject => This subject will complete on the first received complete notification (of, delay in your case)
    – bubbles
    Sep 2, 2020 at 16:14

1 Answer 1

1

This is a known issue, as solution I would suggest extending Subject, to prevent its completion as long as there are others observers listening to it, as demonstrated below:

class RescrictedCompletionSubject<T> extends Subject<T>{

  public complete(): void {
    if (this.observers.length <= 1) super.complete();
  }
  
}

Optionally:

of(1).pipe(delay(1000)).subscribe(mySubject.next, mySubject.error);

Last but not least:

merge(otherObs, delayed).subscribe(mySubject);
5
  • Thank you, this is exactly what I was looking for! Could you explain why repeat works without repeating the events? Sep 3, 2020 at 8:45
  • Can you add some external links to this known issue please ? For me this is the way Subject works
    – bubbles
    Sep 3, 2020 at 8:54
  • @bubbles I didn't suggest it was a bug, nor that there was any thing wrong that needed to be fixed
    – Rafi Henig
    Sep 3, 2020 at 11:58
  • @Cristian Traìna using merge there's no need for repeat operator, as it doesn't complete as long as there's at least one unclosed observable.
    – Rafi Henig
    Sep 3, 2020 at 12:39
  • as apposed to subscribing directly [ of(1).subscribe(mySubject); ] which leads to mySubject completion
    – Rafi Henig
    Sep 3, 2020 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.