Search code examples
rxjsangular2-http

Observable finally not getting fired


This works:

this.http.get('/doesntexist1')
  .finally(() => console.log('finally1'))
  .subscribe(() => { });

But this doesn't:

const obs = this.http.get('/doesntexist2');
obs.finally(() => console.log('finally2'))
obs.subscribe(() => { });

Both URL produce a 404.

I run both and I only see "finally1" being displayed in the console, any idea why?


Solution

  • The difference is that in the second example the .finally is not in the same stream as the .subscribe since you aren't chaining them.

    Your first example creates this stream:

    get -> finally -> subscribe
    

    Your second example creates two branches:

    get -> finally
    get -> subscribe
    

    The finally wont be executed without a subscription after it.

    If you want to build a stream then you need to chain the operators by using the result of the previous operator. It isn't like an in-place operator.