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?
CodePudding user response:
There's an RxJS constant observable that completes immediately. It's called EMPTY
So just return EMPTY. It'll be semantically clearer too.
CodePudding user response:
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({});
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
