6

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.

Tyler Christian
  • 520
  • 7
  • 14
  • I don't understand what the problem or question is exactly. What are you trying to accomplish? – Günter Zöchbauer Jan 24 '17 at 20:40
  • I think you understand it now but just so anyone else reading is clear: I am wanting to get some data ( `tableData` ) and then call a function that uses `tableData`, only if it is was returned. So there will be no errors from attempting to access an index of undefined. – Tyler Christian Jan 24 '17 at 21:10

1 Answers1

8

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);
         }
    );
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • That is what I was missing. I thought that I needed to call the function outside of the data being returned. I have much to learn. Thank you. I see an example for using `finally` to close the socket when using a socket service. That makes sense that it needs to happen regardless of success or failure. Any examples you would care to list for either would be great as well. Thanks again. – Tyler Christian Jan 24 '17 at 21:06
  • 1
    Awesome. Thank you. – Tyler Christian Jan 24 '17 at 21:12