Reputation: 3029
When working with rxjs
, I often subscribe to my source Observable and using the onData
and onError
handlers, attach some logic to take care of each case. That looks something like:
this.myService.myObservable().subscribe(
() => this.onNextData(),
() => this.onErrorData()
);
Then (and sometimes), inside of each of the handlers, I will do the same logic, say, close a modal on success and on failure.
I saw that there is a finalize
operator that I can pipe that will execute some logic based on onComplete
and onError
. However, are both of these states the same? Does an Observable necessarily complete
when it emits data?
Example:
this.myService.myObservable()
// modalClose always happens on success and on failure (?)
.pipe(finalize(() => this.modalClose())
.subscribe(
() => this.onNextData(),
() => this.onErrorData()
);
Upvotes: 2
Views: 782
Reputation: 6844
No, an Observable does not necessarily complete
when it emits data.
Observables, unlike promises, are explicitly designed for multiple emissions - so it makes no sense for them to always complete
after a single emission.
Think of the complete
as the Observable saying "I will never send you more data".
For a very common use-case like making a web request - it is normal that it will either emit a value or an error once and then complete
.
For a different use-case such as one part of the application communicating to another - it is normal that it will send multiple messages and only complete
when the source is removed.
From the documentation:
Observables are lazy Push collections of multiple values. They fill the missing spot in the following table:
Upvotes: 2