Luctia
Luctia

Reputation: 376

Non-completing observables

Somewhere in my application, I have a function that must return an Observable. Most of the time, this works fine, but there is an instance where it's not really possible to provide a meaningful result. If this is the case, the caller won't do anything with the result either.

Because it doesn't really matter what the result is, I return new Observable() here. If I return nothing (like return;), I get an error so I must return an Observable.

The thing I'm worried about is making Observables like these that never complete. At the end of an Observable's lifespan, subscriber.complete() is used to indicate the Observable isn't going to do anything anymore. If I don't do that, will this result in any serious problems, like memory leaks?

Upvotes: 1

Views: 1230

Answers (2)

sky6
sky6

Reputation: 36

There are many types of Observable :

  • finite (like Http requests)
  • infinite

The type of infinite is allowing memory leak or some "bizarre" issues because depend on observable used like replay.

To return observable who complete() now without emit next() value :

return EMPTY;

If you need to pass through next() :

return of({});

Return an empty Observable

My advice is to use a takeUntil in pipe to unsubscribe to avoid memory leak.

https://blog.bitsrc.io/6-ways-to-unsubscribe-from-observables-in-angular-ab912819a78f

Upvotes: 2

Mrk Sef
Mrk Sef

Reputation: 8022

There's an RxJS constant observable that completes immediately. It's called EMPTY

So just return EMPTY. It'll be semantically clearer too.

Upvotes: 2

Related Questions