I don't see very good documentation on what the difference is between do
and finally
in RxJS. My goal is to take action only when an Observable returns data but it looks like they will both take action on failure as well.
do
says "Invokes an action for each element in the observable
sequence and invokes an action upon graceful or exceptional
termination of the observable sequence." The observable might return more than one element?
finally
says "Invoke a
specified action after the source observable sequence terminates
gracefully or exceptionally".My hope is that someone will explain if it matters which is used or if there is a better alternate method.
getData(choice): void {
this.dataService.getTableData(choice, 'mainCalls.php')
.do( () => this.defineWidth() )
.subscribe(tableData => this.tableData = tableData,
err => {
console.log(err);
}
);
}
ngOnInit() {
this.getData('getTableData');
}
defineWidth is a function that is dependent upon the data being returned by the Observable. I'm open to suggestion and reading material on alternate methods to accomplish what I want.
This call also returns an object, the Subscription : const subscription = observable.subscribe((x) => console.log(x));
An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. A Subject is like an Observable, but can multicast to many Observers.
An Observer is a consumer of values delivered by an Observable. Observers are simply a set of callbacks, one for each type of notification delivered by the Observable: next , error , and complete .
Complete value: With the complete value, the observer sends no value. This usually signals that the subscriptions for that particular Observable is complete. If the complete value is sent, nothing else can be delivered to the Observable.
do()
is called for each normal event and does not modify the data stream. It is used only for side effects.
finally()
is called once after the last event or after an error if any. It is called once in either case success or failure.
If this.defineWidth()
depends on this.tableData
than you don't need do
or finally
. Just add the call after the line where you assign the response to this.tableData
:
getData(choice): void {
this.dataService.getTableData(choice, 'mainCalls.php')
.subscribe(tableData => {
this.tableData = tableData;
this.defineWidth();
}),
err => {
console.log(err);
}
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With